单例模式

恶汉式

public class Monitor1 {
        private Monitor1 (){}
        //创建Monitor1的无参构造器
        private static Monitor1 monitor=new Monitor1();
        //先创建Monitor1对象
        //待有需求的时候再调用
        public static Monitor1 getMonitor(){
            return monitor;
        }
}

懒汉式

public class Single {
    private static volatile Single instance;
    private Single() {}
    public static Single getInstance() {
        if (instance == null) {
            synchronized (Single.class) {
                if (instance == null) {
                    instance = new Single();
                }
            }
        }
        return instance;
    }
}
posted @ 2020-01-10 16:18  莫等、闲  阅读(138)  评论(0编辑  收藏  举报