单例模式是结构最简单的设计模式,用于创建软件系统中独一无二的对象;但如果深入研究,单例模式也是最复杂的设计模式
单例模式(Singleton Pattern):确保某一个类只有一个实例,且自行实例化,并向整个系统提供这个实例。单例模式是一种对象创建型模式
单例模式有两种不同的实现方式,饿汉式单例模式(Eager Singleton)和懒汉式单例模式(Lazy Singleton)
本文介绍饿汉式单例模式(Eager Singleton),代码如下
package com.design.singleton;
/**
* 饿汉单例模式
*/
public class EagerSingleton {
private static final EagerSingleton eagerSingleton = new EagerSingleton();
private EagerSingleton(){
}
public static EagerSingleton getInstance(){
return eagerSingleton;
}
}
通过代码可以看出,由于在定义静态变量 eagerSingleton 的时候实例化单例类 EagerSingleton,因此饿汉模式在类被加载时,静态变量 eagerSingleton 就会被初始化,此时类的私有构造函数会被调用,单例类的唯一实例会被创建
调用测试
package com.design.singleton;
public class TestMain {
public static void main(String[] args) {
EagerSingleton ss1 = EagerSingleton.getInstance();
EagerSingleton ss2 = EagerSingleton.getInstance();
System.out.println(ss1);
System.out.println(ss2);
System.out.println( ss1 == ss2);
}
}
饿汉式单例模式(Eager Singleton)的另一种写法,通过静态块实例化对象来实现饿汉模式
package com.design.singleton;
/**
* 静态块饿汉单例模式
*/
public class StaticEagerSingleton {
private static final StaticEagerSingleton staticEagerSingleton;
static {
staticEagerSingleton = new StaticEagerSingleton();
}
private StaticEagerSingleton(){
}
public static StaticEagerSingleton getInstance(){
return staticEagerSingleton;
}
}