Design pattern fifteen, singleton pattern

Singleton mode, to ensure that a class has only one instance, and to provide a global access point to access it

The hungry Chinese singleton instantiates an object and gives it a reference when the singleton class is loaded;

The lazy singleton will only instantiate an object and give it its own reference only when it is actually used.

/*
*饿汉式单例
*我们知道,类加载的方式是按需加载,且加载一次。因此,在上述单例类被加载时,
*就会实例化一个对象并交给自己的引用,供系统使用;而且,由于这个类在整个
*生命周期中只会被加载一次,因此只会创建一个实例,即能够充分保证单例
*/
public class Singleton1 {
    
    
    private static Singleton1 singleton1 = new Singleton1();//创建自己的静态对象
    
    private Singleton1(){
    
        private构造方法,堵死了外界利用new创建此类实例的可能
        
    }
    
    // 以自己实例为返回值的静态的公有方法
    public static Singleton1 getSingleton1(){
    
    
        return singleton1;
    }
}


/*
*懒汉式单例单例实例被延迟加载,即只有在真正使用的时候才会实例化
*一个对象并交给自己的引用
*/
public class Singleton2 {
    
    
    private static Singleton2 singleton2;
    
    private Singleton2(){
    
    
        
    }
    
    // 以自己实例为返回值的静态的公有方法,静态工厂方法
    public synchronized static Singleton2 getSingleton2(){
    
    
        // 被动创建,在真正需要使用时才去创建
        if (singleton2 == null) {
    
    
            singleton2 = new Singleton2();
        }
        return singleton2;
    }
}

From the perspective of speed and response time, the hungry style (also known as immediate loading) is better; in terms of resource utilization efficiency, the lazy style (also known as lazy loading) is better.

Guess you like

Origin blog.csdn.net/weixin_45401129/article/details/114629505