单例设计模式:
饿汉式:public class Single{
private static final Single s = new Single();
private Single(){ };
public static Single getInstance(){
return s;}}
懒汉式:public class Single{
private static Single s = null;
private Single(){}
public static Single getInstance(){
if(s==null){
synchronized(Single.class){
if(s==null) s=new Single();}}
return s;}}
其中懒汉式又称为延迟加载,在具体用到时再实例化。
而饿汉式是类一加载对象就已存在,在实际开发中建议使用饿汉式,不过一般考试会考懒汉式 |