设计模式之单例模式

设计模式之原型模式(TODO)

频繁用到的重复对象 跟远程频繁访问数据库资源的情况下考虑原型模式

单例模式

单例 顾名思义就一个实例 (多线程的情况下也要保证只有一个实例)

单例模式有七种 (常见场景 Spring的单例模式 数据库连接池 全局资源)

1.静态创建

static Xxx X = new XXX();

2.懒汉模式(不安全/加锁安全 但是浪费资源)

package com.example.设计模式.单例模式;

/**
 * @Date:2022/4/12
 * @author: ZLF
 */
public class Xxx {
    private static Xxx x;

    public Xxx() {

    }

    /**
     * 懒加载 线程不安全
     *
     * @return
     */
    public static Xxx getInstance() {
        if (null != x) {
            return x;
        }
        x = new Xxx();
        return x;
    }

    /**
     * 懒加载 线程安全 加了锁
     *
     * @return
     */
    public synchronized static Xxx getInstances() {
        if (null != x) {
            return x;
        }
        x = new Xxx();
        return x;
    }
}

3.饿汉模式

package com.example.设计模式.单例模式;

/**
 * 饿汉模式
 *
 * @Date:2022/4/12
 * @author: ZLF
 */
public class XxxOne {
    /** 一开始就生命了 就不会 抢来抢去*/
    private static XxxOne instance = new XxxOne();

    public XxxOne() {
    }

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

4.内部类调用

static 懒加载

public class XxxClass {
    private static XxxClass xxxClass = new XxxClass();

    private XxxClass() {
    }

    public static XxxClass xxxClass() {
        return xxxClass.xxxClass;
    }


5.双重锁校验机制

package com.example.设计模式.单例模式;

/**
 * @Date:2022/4/12
 * @author: ZLF
 */
public class XxxSynchronized {
    // 懒加载
    private static XxxSynchronized instance;

    public XxxSynchronized() {
    }
    
    public static XxxSynchronized getInstance() {
        if (null != instance) {
            return instance;
        }
        synchronized (XxxSynchronized.class) {
            if (null == instance) {
                instance = new XxxSynchronized();
            }
        }
        return instance;
    }
}

6.CAS (TODO)

7.枚举单例(TODO)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值