设计模式理解之单例模式

来源:互联网 发布:windows入门教程 编辑:程序博客网 时间:2024/05/19 18:47

定      义

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. 

Java中单例模式定义:“一个类有且仅有一个实例,并且自行实例化向整个系统提供。”


实现方法

An implementation of the singleton pattern must:

● ensure that only one instance of the singleton class ever exists; and

● provide global access to that instance.

Typically, this is done by:

● declaring all constructors of the class to be private; and

● providing a static method that returns a reference to the instance.

The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. 


饿汉式实现[Eager initialization]:

The instance is created when the class  is initialized.

public class Singleton {    private static final Singleton INSTANCE = new Singleton();    private Singleton() {    }    public static Singleton getInstance() {        return INSTANCE;    }}

● 实例一开始就被创建,以后不再改变,保证了线程安全

● getInstance()方法不需要加synchronize关键字来解决多线程同步的问题

● final 关键字保证了实例不可变,且只会存在一个


懒汉式实现[Lazy initialization]:

A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked.

public final class Singleton {    private static volatile Singleton instance = null;    private Singleton() {}    public static Singleton getInstance() {        if (instance == null) {            synchronized(Singleton.class) {                if (instance == null) {                    instance = new Singleton();                }            }        }        return instance;    }}
上面是double-checked locking,下面更普遍的写法:
public class LazySingleton {    private static volatile LazySingleton instance = null;    private LazySingleton() {           }    public static synchronized LazySingleton getInstance() {            if (instance == null) {                instance = new LazySingleton ();            }        return instance;    }}

静态内部类方式:

public class Singleton {        private static class LazyHolder {           private static final Singleton INSTANCE = new Singleton();        }        private Singleton (){}        public static final Singleton getInstance() {           return LazyHolder.INSTANCE;        }    }
LazyHolder类会在你需要的时候才会被初始化,而且它不影响Singleton类的其他static成员变量的使用。这个方法是线程安全的并且避免了使用volatile与synchronized。


测      试

public class SingletonTestActivity extends BaseActivity {    private static final String TAG = "SingletonTestActivity";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        Singleton singleton1 = Singleton.getInstance();        singleton1.setName("Katherine");        Log.i(TAG, "singleton1.name = " + singleton1.getName());        Singleton singleton2 = Singleton.getInstance();        singleton2.setName("Bella");        Log.i(TAG, "singleton1.name = " + singleton1.getName());        Log.i(TAG, "singleton2.name = " + singleton2.getName());        if (singleton1 == singleton2) {            Log.i(TAG, "singleton1 is the same as singleton2");        } else {            Log.i(TAG, "singleton1 isn't the same as singleton2");        }        Singleton singleton3 = Singleton.getInstance();        Log.i(TAG, "singleton1.name = " + singleton1.getName());        Log.i(TAG, "singleton2.name = " + singleton2.getName());        Log.i(TAG, "singleton3.name = " + singleton3.getName());    }}
测试结果

I/SingletonTestActivity: singleton1.name = KatherineI/SingletonTestActivity: singleton1.name = BellaI/SingletonTestActivity: singleton2.name = BellaI/SingletonTestActivity: singleton1 is the same as singleton2I/SingletonTestActivity: singleton1.name = BellaI/SingletonTestActivity: singleton2.name = BellaI/SingletonTestActivity: singleton3.name = Bella


参考链接:

http://blog.csdn.net/jason0539/article/details/23297037

http://www.iteye.com/topic/652440

http://hukai.me/java-notes-singleton-pattern/

https://en.wikipedia.org/wiki/Singleton_pattern