此模式也是我们不知不觉就会使用到的设计模式,例如我们将 配置文件映射为对象时,全局获取配置信息都使用此相同的对象。
单例模式,使用在,单例对象的类确保任何情况下都绝对只有同一个实例,整个系统都使用同一个对象。也就是 一个类只能有一个引用和一个实例方法。
根据单例对象的类初始化的不同分为两种构建方式:
懒汉方式,指系统启动完成后,第一次被使用时构建。
饿汉方式,指系统启动时,类装载时构建(即未被使用就已经构建)。
package cn.luoweiying.singleton;
public class SingletonTest {
public static void main(String[] agrs) {
EagerSingleton singleton = EagerSingleton.getSingleton();
EagerSingleton singleton_two = EagerSingleton.getSingleton();
if (singleton == singleton_two) {
System.out.println("两个比较的对象为同一个对象");
}
LazySingleton lazySingleton = LazySingleton.getSingleton();
EnumSingleton instance = EnumSingleton.INSTANCE;
System.out.println(instance);
}
}
class EagerSingleton {
private static EagerSingleton singleton = new EagerSingleton();
private EagerSingleton() {
System.out.println("私有构造,静态代码块初始化此类");
System.out.println("饿汉方式,指系统启动时,类装载时构建(即未被使用就已经构建)");
}
public static EagerSingleton getSingleton() {
return singleton;
}
}
class LazySingleton {
private static LazySingleton singleton = null;
private LazySingleton() {
System.out.println("懒汉方式,指系统启动完成后,第一次被使用时构建");
}
public static LazySingleton getSingleton() {
if (null == singleton) {
synchronized (LazySingleton.class) {
if (null == singleton) {
singleton = new LazySingleton();
}
}
}
return singleton;
}
}
enum EnumSingleton{
//定义一个枚举对象,此对象就是单例对象
INSTANCE;
@Override
public String toString() {
return "枚举创建的单例对象,防止序列化与反序列化破坏单例对象";
}
}
注意:序列化与反序列化会破坏单例对象
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有