设计模式之单例模式

本文深入探讨了单例模式的四种实现方式:饿汉式、懒汉式、内部类及枚举,对比了它们的特点和适用场景,是理解单例模式不可多得的参考资料。

单例模式之饿汉式

/**
 * @Auther: oldmatewang
 * @Description:  单例模式之饿汉式--->该类在被加载时就会实例化一个对象
 */
public class Hungry {
    //构造器私有化
    private Hungry(){}
    //创建所有对象
    private static Hungry HUNGRY  = new Hungry();
    //提供对外接口
    public static Hungry getInstance(){
        return HUNGRY;
    }
}

/**
 * @Auther: oldmatewang
 * @Description: 测试单例模式
 */
public class SingleTest {

    @Test
    public void Hungry(){
        Hungry instance1 = Hungry.getInstance();
        Hungry instance2 = Hungry.getInstance();
        System.out.println(instance1 == instance2);
    }
}

单例模式之懒汉式

/**
 * @Auther: oldmatewang
 * @Description: 单例模式之懒汉式--->该类在被使用的时候才会创建对象
 */
public class LazyMode {
    //构造器私有化
    private LazyMode(){}
    //定义变量,为保证原子可见性 添加volatile关键字
    private static volatile LazyMode lazyMode;
    //提供对外
    public static LazyMode getInstance(){
        //先判断是否为空,如果不为空直接返回该对象,目的时为了减少资源消耗
        if (lazyMode == null){
            //为保证线程安全使用synchronized锁
            synchronized (LazyMode.class){
                //多线程情况下为保证唯一性需要再次进行判空
                if (lazyMode == null){
                    lazyMode = new LazyMode();
                }
            }
        }
        return lazyMode;
    }

}

/**
 * @Auther: oldmatewang
 * @Description:
 */
public class SingleTest {

    @Test
    public void LazyModeTest(){
        LazyMode instance = LazyMode.getInstance();
        LazyMode instance1 = LazyMode.getInstance();
        System.out.println(instance == instance1);
    }
}

单例模式内部类

/**
 * @Auther: oldmatewang
 * @Description: 内部类方式创建单例
 */
public class Outher {
    //私有化构造其
    private Outher(){}
    //定义内部类并实例化对象
    private static class Inner{
        private static final Outher INSTANCE = new Outher();
    }
    //提供对外接口
    public static Outher getInstance(){
        return Inner.INSTANCE;
    }
}

/**
 * @Auther: oldmatewang
 * @Description:
 */
public class SingleTest {

    @Test
    public void InnerClass(){
        Outher instance = Outher.getInstance();
        Outher instance1 = Outher.getInstance();
        System.out.println(instance == instance1);
    }
}

单例模式之枚举

/**
 * @Auther: oldmatewang
 * @Description: 枚举单例模式,推荐使用,安全性高,无法通过反射破坏
 */
public enum SingEnum {
    INSTANCE;
    public static SingEnum getInstance(){
        return INSTANCE;
    }
}


/**
 * @Auther: oldmatewang
 * @Description:
 */
public class SingleTest {

    @Test
    public void SingEnum(){
        SingEnum instance = SingEnum.INSTANCE;
        SingEnum instance1 = SingEnum.INSTANCE;
        Systm.out.println(instance == instance1);
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值