【设计模式】14.单例模式

单例模式

  单例模式(Singleton),保证在运行时,某个类在内存中只有一个对象,并提供一个访问它的全局访问点。

结构图:

 

 例:

// 1.饿汉式,类一加载就实例化对象
public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {     // 构造器私有化
    }

    public static Singleton getInstance(){  // 本类实例的唯一全局访问点
        return instance;
    }
}

 

// 2.懒汉式,第一次被引用时(getInstance),才将自己实例化
public class Singleton{

    private volatile static Singleton instance = null;  // 创建当前对象的引用

    private Singleton(){      // 构造器私有化
    }

    public synchronized static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }

}

 

public class Test {
    public static void main(String[] args) {
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);   // true
    }
}

 

饿汉式:

  仅在类加载时就初始化完成,getInstance的时候,实例已经存在,线程安全,效率相对较高。

 

懒汉式:

  在需要的时候才实例化(getInstance),线程不安全,须加锁(volatile/synchronized)才能使线程安全,所以效率相对低。

 

posted @ 2020-05-09 15:33  Jiazhongxin  阅读(107)  评论(0编辑  收藏  举报