Singleton模式(单例)
此模式也是我们不知不觉就会使用到的设计模式,例如我们将 配置文件映射为对象时,全局获取配置信息都使用此相同的对象。
单例模式,使用在,单例对象的类确保任何情况下都绝对只有同一个实例,整个系统都使用同一个对象。也就是 一个类只能有一个引用和一个实例方法。
单例模式在Java中有两种方式
根据单例对象的类初始化的不同分为两种构建方式:
懒汉方式,指系统启动完成后,第一次被使用时构建。
饿汉方式,指系统启动时,类装载时构建(即未被使用就已经构建)。
示例代码:
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 "枚举创建的单例对象,防止序列化与反序列化破坏单例对象";
}
}
UML类图
注意:序列化与反序列化会破坏单例对象