设计模式(二):Singleton

Singleton:确保在任何情况下,只会产生一个实例

/**
 * @author:xusonglin
 * ===============================
 * Created with IDEA.
 * Date:2019/1/3
 * Time:21:19
 * 一般单例,类加载的时候就创建实例
 * 饿汉式
 * ================================
 */
public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){
        System.out.println("创建了实例");
    }
    private static Singleton getInstance(){
        return instance;
    }
}
/**
 * @author:xusonglin
 * ===============================
 * Created with IDEA.
 * Date:2019/1/3
 * Time:21:22
 * 懒式模式
 * 在需要的时候才进行创建
 * 有线程安全的问题
 * ================================
 */
public class LazySingleton {
    private static LazySingleton ourInstance = null;

    public static LazySingleton getInstance() {
        if(ourInstance == null){
            ourInstance = new LazySingleton();
        }
        return ourInstance;
    }

    private LazySingleton() {
    }
}
/**
 * @author:xusonglin
 * ===============================
 * Created with IDEA.
 * Date:2019/1/3
 * Time:21:25
 * 在懒式上加锁进行线程安全
 * ================================
 */
public class SynchronizedLazySingleton {
    private static SynchronizedLazySingleton instance = null;

    private SynchronizedLazySingleton() {
    }

    private synchronized SynchronizedLazySingleton getInstance(){
        if (instance == null){
            instance = new SynchronizedLazySingleton();
        }
        return instance;
    }
}
package com.ermu.gof.singleton;

/**
 * @author:xusonglin
 *  ===============================
 * Created with IDEA.
 * Date:2019/1/13
 * Time:21:27
 * 双重判断
 * ================================
 */
public class DoubleSynchronizedLazySingleton {
    /**
     * volatile 禁止指令重排序
     *  因为下面代码有重复地方
     */
    private static volatile DoubleSynchronizedLazySingleton singleton = null;

    public DoubleSynchronizedLazySingleton() {
    }

    private static DoubleSynchronizedLazySingleton getSingleton(){
        if(null == singleton){
            synchronized (DoubleSynchronizedLazySingleton.class){
                if (null == singleton){
                    return new DoubleSynchronizedLazySingleton();
                }
                return singleton;
            }
        }
        return singleton;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值