单件模式(单例模式)
这个模式很简单,直接上代码:
public class Singleton { private static Singleton uniqueInstance; private Singleton() {}; public static Singleton getInstance() { if(uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
其中可能出现的问题是,但多线程实例化该类时可能出现实例化多个类,有如下解决方案:
一、这种比较消耗资源,不推荐。
public class Singleton { private static Singleton uniqueInstance; private Singleton() {}; public static synchronized Singleton getInstance() { if(uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
二、改良版,效率高。
public class Singleton { private volatile static Singleton uniqueInstance; // volatile关键字确保多线程正确处理 uniqueInstance private Singleton() {}; public static Singleton getInstance() { if(uniqueInstance == null) { synchronized(Singleton.class) { if(uniqueInstance == null) { // 再检查一次 uniqueInstance = new Singleton(); } } } return uniqueInstance; } }
三、最简单,效率也最高
public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() {}; public static Singleton getInstance() { return uniqueInstance; } }
以上就是单件模式(单例模式),是很简单吧