经典单例模式 123456789101112 public class { private static Singleton uniqueInstance; private (){ } public static Singleton getInstance(){ if(uniqueInstance == null){ uniqueInstance = new Singleton(); } return uniqueInstance; }} 处理多线程时 同步方法 1234567891011121314 public class { private static Singleton uniqueInstance; private (){ } //这种方式会使运行效率大幅下降 public static synchronized Singleton getInstance(){ if(uniqueInstance == null){ uniqueInstance = new Singleton(); } return uniqueInstance; }} “急切” 方式 12345678 public class { private static Singleton uniqueInstance = new Singleton(); private Singleton(){ } public static Singleton getInstance(){ return uniqueInstance; }} “双重检查加锁” 1234567891011121314151617 //jdk1.5 以后版本可用public class Singleton{ private volatile static Singleton uniqueInstance; private Singleton(){ } public static Singleton getInstance(){ if(uniqueInstance == null){ synchronized (Singleton.class){ if(uniqueInstance == null){ uniqueInstance = new Singleton(); } } } return uniqueInstance; }} 赞微海报分享
近期评论