单例模式
单例模式:
单例模式分为懒汉模式和饿汉模式
懒汉模式:这种形式,顾名思义,创建单例是被动的,在有对象需要使用单例的时候才检查是否有实例对象存在
代码示例
1 class Singleton{ 2 private static Singleton instance; 3 private Singleton(){} 4 public Singleton getInstance(){ 5 if(instance == null){ 6 instance = new Singleton(); 7 } 8 return instance; 9 } 10 }
饿汉模式:这种形式,在单例一开始就将实例对象创建好,如果有别的对象访问时,直接返回单例
代码示例
1 class Singleton{ 2 private static Singleton instance = new Singleton(); 3 private Singleton(){} 4 public Singleton getInstance(){ 5 return instance; 6 } 7 }
但是两种模式有自己的利弊,在实际使用的过程中还有更好的选择,同时考虑线程安全的问题,可使用如下方式
1 class Singleton{ 2 private volatile static Singleton instance; 3 private Singleton(){} //私有化构造器 4 public Singleton getInstance(){ 5 if(instance == null){ 6 synchronized(Singleton.class){ 7 if(instance == null){ 8 instance = new Singleton(); 9 } 10 } 11 }
return instance; 12 } 13 }
通过volatile关键字和synchronized关键字来保证安全性。
volatile关键字:当instance变量被初始化成Singleton实例时,多个线程可以正确的处理instance变量。
每天努力一点点,加油!

浙公网安备 33010602011771号