单件模式(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;
- }
- }
- //这个相对最为合理