实现单例模式(Java版)!

题目: 设计一个类,我们只能生成该类的一个实例

public class _02_实现单例模式 
}


//单例枚举模式,天然防止反射破坏!
enum Enum {
    INSTANCE;

    public Enum getInstance() {
        return INSTANCE;
    }

}

//恶汉式
class Hungry {
    private static Hungry instance = new Hungry();

    private Hungry() {

    }

    public Hungry getInstance() {
        return instance;
    }
}

//懒汉式
class LazyMan {
    private static volatile LazyMan instance;

    private LazyMan() {
    }

    public static LazyMan getInstance() {
        if (instance == null) {
            synchronized (LazyMan.class) {
                if (instance == null) {
                    instance = new LazyMan();
                }
            }
        }
        return instance;
    }
}

//静态内部类
class Singleton {
    private Singleton() {
    }

    private static class inner {
        private static final Singleton instance = new Singleton();
    }

    public static Singleton getInstance() {
        return inner.instance;
    }
}


猜你喜欢

转载自blog.csdn.net/weixin_45399846/article/details/107449133
今日推荐