单例设计模式(懒汉式、饿汉式)

单例模式

饿汉式

    class Singleton {
    /**
     * 单例模式---饿汉式
     */

    private static final Singleton s = new Singleton();

    private Singleton() {
    }

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

懒汉式

    class SingletonLazy {
    /**
     * 单例模式---懒汉式
     */

    private static SingletonLazy s;

    private SingletonLazy() {
    }

    /**
     * 解决并发线程不安全问题
     */
    public synchronized static SingletonLazy getInstance() {
        if (null == s)
            s = new SingletonLazy();
        return s;
    }
}
posted @ 2020-01-07 11:39  fyangami  阅读(419)  评论(0)    收藏  举报