面试题(三)

单例模式

饿汉式:
public class SingletonDemo{
    //创建一个静态类对象    
    private static SingletonDemo instance = new SingletonDemo(); 
    //修饰符限定为private,避免了类在外部被实例化   
    private SingletonDemo(){
    }  
    public static SingletonDemo getInstance(){
        return instance;
    }
}
懒汉式:
public class SingletonDemo{  
    private static SingletonDemo instance = null;  
    private SingletonDemo(){
    }
    public static synchronized SingletonDemo getInstance(){
        if(instance == null){
            instance = new SingletonDemo();
        }
        return instance;
    }
}

猜你喜欢

转载自blog.csdn.net/kbh528202/article/details/80502467