单例----设计模式

何为单例设计模式,是指在系统运行的过程中,只产生一个实例,参见的有饱汉模式、饿汉模式和静态内部当然还有其他的(例如枚举,双重检查锁实现单例模式),一般用静态内部类。

1、饿汉模式,很饥渴,首先就创建实例了,所以称作为饿汉,它不用加同步关键字,因为是静态属性,所以在没有实例化对象之前就已经在内存中存在故线程安全,但没有实现懒加载,

/**

 *不要实现 Cloneable接口 否则能克隆出新的实例 
 * 测试饿汉式单例模式 
 */
public class SingletonDemo1  implements Serializable {

//类初始化时,立即加载这个对象(没有延时加载的优势)。加载类时,天然的是线程安全的!
private static SingletonDemo1 instance = new SingletonDemo1();  

private SingletonDemo1(){ //私有化构造器
if(instance!=null){
throw new RuntimeException();
}
}



//方法没有同步,调用效率高!
public static SingletonDemo1  getInstance(){
return instance;
}



//反序列化时,如果定义了readResolve()则直接返回此方法指定的对象。而不需要单独再创建新对象!
private Object readResolve() throws ObjectStreamException {
return instance;
}

}

2、饱汉设计模式

/**

 *不要实现 Cloneable接口 否则能克隆出新的实例 
 * 测试饿汉式单例模式
 *
 */
public class SingletonDemo2 implements Serializable {

//类初始化时,立即加载这个对象(没有延时加载的优势)。加载类时,天然的是线程安全的!
private static SingletonDemo2 instance =null;  

private SingletonDemo2(){ //私有化构造器
if(instance!=null){
throw new RuntimeException();
}
}



//方法同步,调用效率低!
public static  synchronized SingletonDemo2  getInstance(){
if(instance==null){
instance = new SingletonDemo2();
}
return instance;
}



//反序列化时,如果定义了readResolve()则直接返回此方法指定的对象。而不需要单独再创建新对象!
private Object readResolve() throws ObjectStreamException {
return instance;
}

}

3、静态内部内设计模式

/**
 * 测试静态内部类实现单例模式
 * 这种方式:线程安全,调用效率高,并且实现了延时加载!
 *
 */
public class SingletonDemo3 implements Serializable {

private static class SingletonClassInstance {
private static final SingletonDemo3 instance = new SingletonDemo3();
}

private SingletonDemo3(){

if(instance!=null){
throw new RuntimeException();
}

}

//方法没有同步,调用效率高!
public static SingletonDemo3  getInstance(){
return SingletonClassInstance.instance;
}

//反序列化时,如果定义了readResolve()则直接返回此方法指定的对象。而不需要单独再创建新对象!
private Object readResolve() throws ObjectStreamException {
return instance;
}


}


你可能感兴趣的:(java)