设计模式之单例模式 懒汉式与饿汉式

需求:在程序中的任何地方,我们想要获取一个类的唯一对象。我们称之为单例模式。

Singleton类

(1)提供一个私有的静态的本类型的成员变量。

(2)构造器私有化

(3)提供公有的静态的方法获取本类中创建的实例(对象)。

饿汉式:加载期间就实例化对象。

public class Singleton{

    private static Singleton instance = new Singleton();

    private Singleton(){}

    public static Singleton getInstatace(){

        return instance;

扫描二维码关注公众号,回复: 2536631 查看本文章

    }

}

懒汉式写法:调用方法时才创建对象

public class Singleton{

    private static Singleton instance;

    private Singleton(){}

    public static Singleton getInstance(){

        if(instance == null){

            instance = new Singleton();

        }

        return instance;

    }

}

猜你喜欢

转载自blog.csdn.net/Betty_betty_betty/article/details/81393268