设计模式系列--设计模式之 单例模式

善学如春起之苗,不见其增,日有所长。假学如磨刀之石,不见其亏,日有所损。

单例模式: 顾名思义 他只有一个实例. 如果这个时候让你写一个单例模式 你怎么写.

  1. 首先 如果是一个单例的话 那他肯定不能实例化多次 他的实例 一定是一个私有的
1private static SingletonModel singletonModel = new SingletonModel();2private static SingletonModel singletonModel = null;

这里有两点
(1) 直接实例化这个对象 在类加载的时候就实例化 这个时候就是饿汉式
(2) 这个时候不实例化这个对象 在获取实例化的时候才去加载 这就是懒汉式(懒加载)

  1. 既然是一个单例 那他的无参构造肯定是私有的 不能直接实例化的
    private SingletonModel() {
    }

3.获取实例化的方法

(1)如果是饿汉式的话直接返回就行了

    public static SingletonModel getInstance() {
        return singletonModel;
    }

(2)如果懒汉的话判空一下 ;

    public static SingletonModel getInstance() {
        if (null == singletonModel) {
            singletonModel = new SingletonModel();
        }
        return singletonModel;
    }

如果是懒汉的话这里要考虑并发 也就是线程安全的问题了 多线程同时获取怎么办
可以通过 synchronized 方式来获取

    public synchronized static SingletonModel getInstance() {
        if (null == singletonModel) {
            singletonModel = new SingletonModel();
        }
        return singletonModel;
    }

二 静态内部类来实现

这里是由于类的静态属性只会在第一次加载类的时候初始化 实现的

/**
 * 懒汉和饿汉
 *
 * @author dongzhiwei
 * @date 2020/8/12 15:00
 */
public class SingletonModel {

    //首先 如果是一个单例的话 那他肯定不能实例化多次 他的实例 一定是一个私有的
    private static SingletonModel singletonModel = null;

    private SingletonModel() {
    }

    private static class  SingletonModelHoler{
        public static SingletonModel singletonModel = new SingletonModel();
    }

    public synchronized static SingletonModel getInstance() {
        return SingletonModelHoler.singletonModel;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值