设计模式 —— 单例
@(Android)
单例模式
单例模式(Singleton Pattern):确保一个类只有一个实例,并提供一个访问它的全局访问点。
- 单例类只能有一个实例
- 单例类必须自己创建自己的唯一实例
- 单例类必须提供一个全局访问的方法
在单例模式的实现过程中,需要注意如下三点:
- 单例类的构造函数为私有;
- 提供一个自身的静态私有成员变量;
- 提供一个公有的静态工厂方法。
懒汉式
懒汉式(Lazy initialization):在调用方法时创建类的实例
An alternate simpler and cleaner version
public final class SingletonDemo {
private static SingletonDemo instance;
private SingletonDemo() { }
public static synchronized SingletonDemo getInstance() {
if (instance == null) {
instance = new SingletonDemo();
}
return instance;
}
}
This method uses double-checked locking(双重校验锁)
public final class SingletonDemo {
private static volatile SingletonDemo instance;
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null ) {
synchronized (SingletonDemo.class) {
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
}
饿汉式
饿汉式(Eager initialization):在类加载时就创建类的实例
If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization, which always creates an instance:
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}