设计模式系列--Singleton
一.类图
二.意图
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
三.适用性
a) 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
b) 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。
四.实现方式
1. 懒汉模式
package explore.singleton;
//懒汉模式
//直到第一次调用的时候再初始化
public class Singleton1 {
private static Singleton1 instance = null;
private Singleton1() {
}
public static synchronized Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
}
2. 饿汉模式
package explore.singleton;
//饿汉模式、
//声明的时候即初始计划
public class Singleton2 {
private static Singleton2 instace = new Singleton2();
private Singleton2() {
}
public static Singleton2 getInstance() {
return instace;
}
}
3. 双重检查模式
package explore.singleton;
//双重检查模式
//并不是安全的:http://www.ibm.com/developerworks/cn/java/j-dcl.html
public class Singleton3 {
private static volatile Singleton3 instance = null;
private Singleton3() {}
public static Singleton3 getInstance() {
if(instance == null) {
synchronized(Singleton3.class) {
if(instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}
五.Runtime类中的单例模式
public class Runtime {
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
不解释:一目了然。