设计模式-单态模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ITzhongzi/article/details/88557294

概要: 保证一个类仅有一个实例,只提供一个访问它的全局访问点。

应用场景

在我们的windows桌面上,我们打开了一个回收站,当我们试图再次打开一个新的回收站时,Windows系统并不会为你弹出一个新的回收站窗口。,也就是说在整个系统运行的过程中,系统只维护一个回收站的实例。

示例demo
  • 单例模式代码:
public class Phone {
    private Phone(){

    }

    private static Phone phone;

    public static Phone getInstance(){
        if(phone == null) {
            phone = new Phone();
            System.out.println("创建 新实例");
        }
        System.out.println("未创建新实例");
        return phone;
    }
}

  • 测试demo
public class Test {
    public static void main(String[] args) {
        Phone instance = Phone.getInstance();
        Phone instance2 = Phone.getInstance();
        Phone instance3 = Phone.getInstance();
        Phone instance4 = Phone.getInstance();
        Phone instance5 = Phone.getInstance();
        Phone instance6 = Phone.getInstance();

    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ITzhongzi/article/details/88557294