Java设计模式之单例模式

前言

这漠北风沙的回音
到底滚烫了谁的爱情
我不敢靠近
前世的风景

简介

设计模式(Design Pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结,使用设计模式是为了可重用代码、让代码更容易被他人理解并且保证代码可靠性。

单例模式

单例模式是确保一个类在内存中只能有一个对象存在,由自身初始化实例并向整个系统提供这个实例。

初始化

  • 懒汉式
public class LazyInstance {

    private static LazyInstance instance;

    private LazyInstance() {
    }

    public static synchronized LazyInstance getInstance() {
        if (instance == null) {
            instance = new LazyInstance();
        }
        return instance;
    }
}
  • 饿汉式
public class HungryInstance {

    private static final HungryInstance INSTANCE = new HungryInstance();

    private HungryInstance() {
    }

    public static HungryInstance getInstance() {
        return INSTANCE;
    }
}
  • 内部类
public class InnerClassInstance {

    private InnerClassInstance() {
    }

    public static InnerClassInstance getInstance() {
        return SingleHolder.INSTANCE;
    }

    private static class SingleHolder {
        private static final InnerClassInstance INSTANCE = new InnerClassInstance();
    }
}
  • 双重加锁
public class DoubleCheckInstance {

    private static volatile DoubleCheckInstance instance;

    private DoubleCheckInstance() {
    }

    public static DoubleCheckInstance getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckInstance.class) {
                if (instance == null) {
                    instance = new DoubleCheckInstance();
                }
            }
        }
        return instance;
    }
}
  • 枚举
public enum EnumInstance {

    INSTANCE
}

源码链接

https://github.com/kuangxiaoguo0123/JavaDesignPatterns

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值