单件模式(Singleton Pattern):确保一个类只有一个实例,并提供一个全局访问点.
注:某些类拥有多个实例是不必要,不安全的,比如注册表管理理,线程池,连接池等等
- class Singleton
- {
- private static Singleton uniqueInstance;
- private Singleton()
- {
- }
- public static Singleton getInstance()
- {
- if (uniqueInstance == NULL)
- uniqueInstance = new Singleton();
- return uniqueInstance;
- }
- }
- //这个可能会在多线程中创建多个实例
- class Singleton1
- {
- private static Singleton uniqueInstance=new Singleton();
- private Singleton1()
- {
- }
- public static Singleton getInstance()
- {
- return uniqueInstance;
- }
- }
- //这个不能达到延迟实例化的效果
- class Singleton2
- {
- private static Singleton uniqueInstance;
- private Singleton2()
- {
- }
- public static synchronized Singleton getInstance()
- {
- if (uniqueInstance == NULL)
- uniqueInstance = new Singleton();
- return uniqueInstance;
- }
- }
- //这个影响getInstance()的性能
- class Singleton3
- {
- private volatile static Singleton uniqueInstance;
- private Singleton3()
- {
- }
- public static Singleton getInstance()
- {
- if(uniqueInstance==null)
- {
- synchronized(Singleton.class)
- {
- if(uniqueInstance==null)
- uniqueInstance=new Singleton();
- }
- }
- return uniqueInstance;
- }
- }
- //这个相对最为合理
本文详细介绍了单例模式的概念及其在不同场景下的实现方式,包括基本的单例模式、线程安全的单例模式以及延迟加载的单例模式等,并探讨了它们各自的优缺点。
1972

被折叠的 条评论
为什么被折叠?



