基于Java的单例模式

懒汉式(静态内部类模式)

public class Singleton {
    
    

    private Singleton() {
    
    
    
    }

    public static Singleton getInstance() {
    
    
        return Holder.INSTANCE;
    }

    private static class Holder {
    
    
        private static final Singleton INSTANCE = new Singleton();
    }
}

饿汉式

public class Singleton {
    
    
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
    
    
    
    }

    public static Singleton getInstance() {
    
    
        return INSTANCE;
    }
}



参考链接:https://www.imooc.com/wiki/Designlesson/singleton.html

猜你喜欢

转载自blog.csdn.net/chuanyu2001/article/details/113897867