单例模式算的上是一种最简单的设计模式了,甚至有些爸爸认为它都算不上是一种模式,顶多算的上算是一种设计技巧。
所谓单例模式,就是一个类有且只能有一个实例,他需要自行创建一个实例并且开放给系统。这种设计模式在我们的项目中十分常见,比如多线程的线程池,比如数据库的连接
池等等。
单例模式能够保证一个类仅有唯一的实例,并提供一个全局访问点。
对于单例模式,这里介绍五种实现方式。
1.懒汉模式:(类加载时不初始化,类加载快,对象获取较慢)
public class Test {
private static Test intance;
private Test(){ //私有构造函数
}
public static synchronized Test getInstance(){//静态,同步,公开访问点
if(intance == null){
intance = new Test();
}
return intance;
}
}
2.饿汉模式(在类加载时就完成了初始化,类加载较慢,获取对象块)
public class Test {
private static Test instance = new Test();//静态私有成员,已初始化
private Test() {
//私有构造函数
}
public static Test getInstance(){ //静态,不用同步(类加载时已初始化,不会有多线程的问题)
return instance;
}
}
3.双重锁模式(在同步内外分别加一次instance == null 的判断,有两次检验,所以称之为双重检验锁)
public class Test {
private volatile static Test instance;
private Test (){}
public static Test getSingleton() {
if (instance == null) {
synchronized (Test.class) {
if (instance == null) {
instance = new Test();
}
}
}
return instance;
}
}
4.静态内部类(一种比较推荐的方法,不存在线程安全问题,同时也没有性能上的缺陷)
public class Test {
private static class SingletonHolder {
private static final Test INSTANCE = new Test();
}
private Test (){}
public static final Test getInstance() {
return SingletonHolder.INSTANCE;
}
}
5.枚举
枚举是jdk1.5以后所添加的新特性,写法简单,没有线程安全问题,但是用的人比较少,也不知道为什么。
public enum Test {
INSTANCE;
}
参考文献:http://blog.youkuaiyun.com/nsw911439370/article/details/50456231