[size=large;]
单列模式:[/size][size=small;]确保一个类只有一个实例,并提供一个
全局访问点。[/size]
?
?
?
package com.renpeng.singleton;/** * 同步单例模式(延迟实例化) * @author administrator * */public class singleton { private static singleton singleton; private singleton(){} public synchronized singleton getinstance(){ if(singleton==null){ singleton=new singleton(); } return singleton; } }
?
?
?
package com.renpeng.singleton;/** * 急切单例模式(非延迟实例话) * @author administrator * */public class singleton1 { private static singleton1 singleton1=new singleton1(); private singleton1(){} public singleton1 getinstance(){ return singleton1; }}
?
?
?
?
?
package com.renpeng.singleton;/** * 双层检测单例模式 * @author administrator * */public class singleton2 { private volatile singleton2 singleton2; private singleton2(){} public singleton2 getinstance(){ if(singleton2==null){ //同步块,首次创建才同步 synchronized (singleton2.class) { if(singleton2==null){ singleton2=new singleton2(); } } } return singleton2; }}
?