确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例
优点:
1. 减少了内存开支
2. 减少了系统的性能开销
3. 避免对资源的多重占用
4. 可以在系统设置全局的访问点,优化和共享资源访问
缺点:
1. 单例模式一般没有接口,扩展很困难,
2. 对测试是不利的
3. 与单一职责原则有冲突
锇汉模式
public class Singleton {
private static final Singleton SINGLETON = new Singleton();
private Singleton() {
}
public static Singleton getSINGLETON() {
return SINGLETON;
}
}
懒汉模式
public class Singleton {
private static Singleton SINGLETON = null;
private Singleton() {
}
public synchronized static Singleton getSINGLETON() {
if(SINGLETON == null){
SINGLETON = new Singleton();
}
return SINGLETON;
}
}
单例扩展:固定个数实例
public class SingletonExtension {
private static int maxNum = 3;
private static List<SingletonExtension> list = new ArrayList<SingletonExtension>();
static {
for (int i = 0; i < maxNum; i++) {
list.add(new SingletonExtension());
}
}
private SingletonExtension() {
}
public static SingletonExtension getSingletonExtension() {
Random random = new Random();
int randomNum = random.nextInt(maxNum);
return list.get(randomNum);
}
}