/*这个是先初始化对象,成为饿汉式**/
class Single{
private Single(){};
private static final Single s=new Single();
public static Single getInstance(){return s;}
}
class SingleDemo{
public static void main(string[] args){
Single ss=Single.getInstance();
}
}
单例设计模式二:
/*对象时方法被调用时,才初始化,对对象的延时加载,称为懒汉式**/
class Single{
private static Single s=null;
private static Single(){};
public static Single getInstance(){
if(s==null){
synchronized(Single.class);
if(s==null)s=new Single();
return s;
}
}
} |
|