单例模式用的比较多的一个设计模式。不多说直接上代码 。
一、懒汉式
public class Demo01 {
private static Demo01 singleton;
private Demo01() {
}
public static synchronized Demo01 getInstance() {
if (singleton == null) {
singleton = new Demo01();
}
return singleton;
}
/**
* 防止反序列化获取多个对象的漏洞。
* 无论是实现Serializable接口,或是Externalizable接口,当从I/O流中读取对象时,readResolve()方法都会被调用到。
* 实际上就是用readResolve()中返回的对象直接替换在反序列化过程中创建的对象。
* 做项目时不需要写这个 如果是产品 让别人调用最好写上。除了枚举 其他单例模式都一样
* @return
* @throws ObjectStreamException
*/
private Object readResolve() throws ObjectStreamException {
return singleton;
}
}
二、饿汉式
public class Demo02 {
private static Demo02 singleton = new Demo02();
private Demo02() {
}
public static synchronized Demo02 getInstance() {
return singleton;
}
}
三、双重校验锁
public class Demo03 {
private volatile static Demo03 singleton = null;
private Demo03() {
}
/**
* 双层校验 JDK1.5之前不推荐 事实上我也没用过这个
* 只是知道有这么一种写法
* @return
*/
public static Demo03 getInstance() {
if(singleton == null){
synchronized (singleton) {
if(singleton == null){
singleton = new Demo03();
}
}
}
return singleton;
}
}
四、枚举
public enum Demo04 {
//单例对象
SINGLETON;
//下面和class一样 该怎么写就怎么写
}
五、静态内部类
public class Demo05 {
private static class SingletonHolder{
private static Demo05 singleton = new Demo05();
}
private Demo05(){}
public static Demo05 getInstance(){
return SingletonHolder.singleton;
}
}