有关单例模式的总结
单例模式,顾名思义就是只有一个实例,自己负责创建自己的对象,这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
单例模式创建方式主要有以下几种:
懒汉式
public class SinglonTest {
private static SinglonTest instance = null;
private SinglonTest(){}
public static synchronized SinglonTest getInstance(){
if (instance == null){
instance = new SingonTest();
}
return instance;
}
}
饿汉式
public class SinglonTest {
private static SinglonTest instance = new SinglonTest();
private SinglonTest(){}
public static SinglonTest getInstance(){
return instance;
}
}
双检锁
public class SinglonTest {
private static SinglonTest instance = null;
private SinglonTest(){}
public static SinglonTest getInstance(){
if (instance == null){
synchronized(SinglonTest.class){
if (instance == null){
instance = new SingonTest();
}
}
return instance;
}
}
静态内部类
public class SinglonTest {
private static class SinglonTestHolder {
private static final SinglonTest INSTANCE= new SinglonTest();
}
private SinglonTest(){}
public static SinglonTest getInstance(){
return SinglonTestHolder.INSTANCE;
}
}
评论