单例(Singleton)设计模式保证每个类只有一个实例,并为这个实例提供一个全局的访问点。
与工具类中的静态成员不同,单例类一般用来保存应用程序的状态数据,这些数据在应用程序的各个部分都可能被访问或修改。
单例模式的几种实现方式。
| public class Singleton{ private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } /** Don't let anyone else instantiate this class */ private Singleton() { } } |
| public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } |
| public class Singleton { private static Singleton instance = null; private Singleton(){ } synchronized static public Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } |
| public class Singleton { private static Singleton instance; private Singleton(){ } public static Singleton getInstance() { if (instance == null){ synchronized(Singleton.class){ if(instance == null) { instance = new Singleton(); } } } return instance; } } |
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/348874/viewspace-735429/ ,如需转载,请注明出处,否则将追究法律责任。