单例模式创建

饿汉式

public class Singleton{
    public final static INSTANCE = new Singleton();
    private Singleton(){
        
    }
}
/*枚举类型限制对象个数,当我们只写一个就变成了单例模式
*/
public enum Singleton(){
    INSTANCE
}
public class Singleton{
    public static final INSTANCE;
    String info;
    static{
        //适合创建对象是否需要一些文件的初始化之类的工作
        Propereties pro = new Propereties();
        pro.load(Singleton.class.getClassLoader().getResourcesAsStream(类路径下的文件));
        INSTANCE = new Singleton(pro.property("info"));
    }
    privat Singleton(String info){
        this.info = info;
    }
}

懒汉式

//线程不安全
public class Singleton{
    private static final INSTANCE;
    private Singleton(){
        
    }
    public Singleton getInstance(){
        if(INSTANCE == null){
	      INSTANCE = new Singleton();
        }
        return INSTANCE;
    }
}
//线程安全
public class Singleton{
    private static final INSTANCE;
    private Singleton(){
        
    }
    public Singleton getInstance(){
 		synchronized(Singleton.class){//加锁
        if(INSTANCE == null){
		INSTANCE = new Singleton();
        }
        return INSTANCE;
        }
    }
}
//线程安全:静态内部类
public class Singleton{
    
    public static class Inner{
        private static final INSTANCE = new Singleton();
    }
       public Singleton getInstance(){

        return Inner.INSTANCE;
    }
    
}
posted @ 2020-07-31 17:00  浅滩浅  阅读(85)  评论(0编辑  收藏  举报