单例模式之饿汉式
/**
* @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);
}
}
本文深入探讨了单例模式的四种实现方式:饿汉式、懒汉式、内部类及枚举,对比了它们的特点和适用场景,是理解单例模式不可多得的参考资料。
879

被折叠的 条评论
为什么被折叠?



