设计模式之单例模式

定义

单例模式是指在任何情况下一个类只有一个实例,并提供一个全局访问点

饿汉式单例

在单例类首次加载的时候就创建实例

public class SingletonTest {

    private static final SingletonTest singleton = new SingletonTest();

    private SingletonTest() {
    }

    public static SingletonTest getInstance() {
        return singleton;
    }
}
懒汉式单例

被外部类调用时才创建

public class SingletonTest {

    private volatile static SingletonTest singleton;

    private SingletonTest() {
    }

    /**
     * 线程不安全
     * @return
     */
    public static SingletonTest getInstance() {
        if(null == singleton) {
            singleton = new SingletonTest();
        }
        return singleton;
    }

    /**
     * 双重检查
     * @return
     */
    public static SingletonTest getInstance2() {
        if(null == singleton) {
            synchronized (SingletonTest.class) {
                if(null == singleton) {
                    singleton = new SingletonTest();
                }
            }
        }
        return singleton;
    }
}

静态内部内写法,静态内部类在用的时候才会分配内存

public class SingletonTest {

    private SingletonTest() {}

    public static SingletonTest getInstance() {
        return LazySingleton.INSTANCE;
    }

    private static class LazySingleton {
        private static final SingletonTest INSTANCE = new SingletonTest();
    }
}
枚举式单例

自动支持序列化机制,绝对防止多次实例化

public enum SingletonTest {

    INSTANCE;

    private LazySingleton lazySingleton;

    public LazySingleton getInstance() {
        return INSTANCE.lazySingleton;
    }

    private SingletonTest() {
        lazySingleton = new LazySingleton();
    }

    private static class LazySingleton {

    }
}
容器式单例

将每一个实例都缓存到统一的容器中,使用唯一标识获取实例,容器式单例适用于创建实例非常多的情况

public class SingletonTest {

    private static final Map<String, Class> ioc = new ConcurrentHashMap<>();

    public static Class getBean(String className) throws ClassNotFoundException {
        if(!ioc.containsKey(className)) {
            ioc.put(className, Class.forName(className));
        }
        return ioc.get(className);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值