单利设计模式设计

public class singleTon {
    /**
     * 懒汉式:对象被调用时才创建
     * 
     * 静态方法无法调用不是静态变量
     */
        private static singleTon singleton;
        /**
         * 实例化方法,必须通过对象调用
         * 设置为静态方法
         * @return
         */
        public static singleTon newIntance() {
            if(singleton==null) {
                singleton=new singleTon();
            }
            return singleton;
            
        }
}

由于添加了锁,所以效率比较的低

 

饿汉式解决懒汉式线程问题

public class singleTon1 {
    /**
     * 饿汉式:类加载时就会被调用
     * 
     * 静
     */
        private static singleTon1 singleton =new singleTon1();
        /**
         * 实例化方法,必须通过对象调用
         * 设置为静态方法
         * @return
         */
        public static singleTon1 newIntance() {
            
            return singleton;
            
        }
}

 

posted @ 2019-10-28 22:10  konge!  阅读(99)  评论(0编辑  收藏  举报