单例设计模式(Single case design mode)

理解

所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例。

饿汉式和懒汉式的区别

饿汉式:先创建对象,后使用。(对象加载需要时间)
懒汉式:使用的时候再创建对象。(延迟对象的创建)

代码实现

//饿汉式
class Hungry{
    //1.内部创建类的对象
    private static Hungry hungry = new Hungry();
    //2.私有化类的构造器
    private Hungry(){
    }
    //3.提供公共的静态方法,返回类的对象
    public static Hungry getHungry(){
        return hungry;
    }
}
//懒汉式
class Lazy{
    //1.内部声明类的对象
    private static Lazy lazy = null;
    //2.私有化类的构造器
    private Lazy(){
    }
    //3.提供公共的静态方法,返回类的对象
    public static Lazy getLazy(){
        if(lazy == null){
            synchronized (Lazy.class){
                if(lazy == null){
                    lazy = new Lazy();
                }
            }
        }
        return lazy;
    }
}
————————

understand

The so-called single class design method can only guarantee the existence of a certain class in the whole software system.

The difference between hungry and lazy

Hungry Chinese style: create objects first and then use them. (object loading takes time)
Lazy: create objects when you use them. (delay object creation)

code implementation

//饿汉式
class Hungry{
    //1.内部创建类的对象
    private static Hungry hungry = new Hungry();
    //2.私有化类的构造器
    private Hungry(){
    }
    //3.提供公共的静态方法,返回类的对象
    public static Hungry getHungry(){
        return hungry;
    }
}
//懒汉式
class Lazy{
    //1.内部声明类的对象
    private static Lazy lazy = null;
    //2.私有化类的构造器
    private Lazy(){
    }
    //3.提供公共的静态方法,返回类的对象
    public static Lazy getLazy(){
        if(lazy == null){
            synchronized (Lazy.class){
                if(lazy == null){
                    lazy = new Lazy();
                }
            }
        }
        return lazy;
    }
}