设计模式(1)单例模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bj_ameng/article/details/89325695
  1. 懒汉式
/**
 * 懒汉式
 */
public class Singleton {

    private static Singleton instance;

    private Singleton() {
    }

    /**
     * 加上synchronized 变成线程安全
     *
     * @return
     */
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

}
  1. 饿汉式
/**
 * 饿汉式
 */
public class Singleton1 {

    private static Singleton1 instance = new Singleton1();
    ;

    private Singleton1() {
    }

    public static Singleton1 getInstance() {
        return instance;
    }
}

猜你喜欢

转载自blog.csdn.net/bj_ameng/article/details/89325695
今日推荐