美文网首页
单例模式(java)

单例模式(java)

作者: 小淼不卖萌 | 来源:发表于2018-08-24 16:17 被阅读0次
    • 单例模式可以保证系统中,应用该模式的类一个类只有一个实例
    • 一个类只有一个对象实例

    基于java的单例模式实现

    public class En {
        public static void main(String[] args) {
    //      饿汉单例
            for (int i=0; i< 100; i++) {
                A tmp = A.getInstance();
                System.out.println(tmp);
            }
    //      懒汉单例
            for (int i=0; i< 100; i++) {
                B tmp = B.getInstance();
                System.out.println(tmp);
            }
        }
    }
    
    //单例模式--饿汉
    //在类初始化时调用
    class A{
        public A() {
            System.out.println("hello...");
        }
        private static final A tmp_a = new A();
        private static int count = 0;
        public static A getInstance() {
            count += 1;
            System.out.println(count);
            return tmp_a;
        }
    }
    
    //单例模式--懒汉
    //在第一次调用时实例化
    class B{
        public B() {
            System.out.println("hello...bbbb");
        }
        private static B tmp_b = null;
        private static int count = 0;
        public static B getInstance() {
            System.out.println(count++);
            if (tmp_b == null) {
                tmp_b = new B();
            }
            return tmp_b;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:单例模式(java)

          本文链接:https://www.haomeiwen.com/subject/szfiiftx.html