GOF 23 设计模式之创造者模式 -----单例模式

创建者设计模式之单例模式
  • 1.饿汉式
  • 2.懒汉式
  • 3.双重检测锁(不推荐,可能会有bug)
  • 4.静态内部类
  • 5.枚举
//饿汉式 -- 常用 速度快 但是无法延时加载
class Sigleton1 {
    private static final Sigleton1 Instance = new Sigleton1(); //由于static的原因,不会有多线程下的问题

    private Sigleton1(){
    }

    public static Sigleton1 getInstance(){
        return Instance;
    }

}
//懒汉式 -- 不常用 可以实现延时加载,但是由于要使用锁,所以速度很慢。
class Sigleton2{
    private static Sigleton2 Instance;

    private Sigleton2(){

    }
    public static synchronized Sigleton2 getInstance(){
        if(Instance == null){
            Instance = new Sigleton2();
        }

        return Instance;
    }
}

//双重检测锁模式 -- 不用  可以减少懒汉式所造成的时间过长
class Sigleton3{
    private static Sigleton3 Instance;

    private Sigleton3(){
    }

    public static Sigleton3 getInstance(){
        if (Instance == null){
            synchronized (Sigleton3.class){
                if (Instance == null){
                    Instance = new Sigleton3();
                }
            }
        }
        return Instance;
    }
}
//静态内部类  --常用 可以延时加载 速度快 

class Sigleton4{
//静态内部类只有在调用时才会初始化
    private static class Sigleton{

        private static final Sigleton Instance = new Sigleton();
        Sigleton(){
        }

    }

    public static Sigleton getInstance(){
        return Sigleton.Instance;
    }
}


//枚举--天然单例 不可以延时加载 速度快 可以防止反射

enum Sigleton5{
    INSTANCE();
    Sigleton5(){
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值