一.介绍
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。即采取一定方法保证在整个软件系统中,某个类只能存在一个实例对象,并且该类只提供一个取得其对象实例的方法,这个方法是静态的。
简而言之:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
主要目的是保证一个类仅有一个实例,并提供一个访问它的全局访问点。用到单例模式创建的类一般是一个全局使用而且频繁地创建与销毁的类,通过单例模式,可以节省系统资源开销。
核心标注:构造函数是私有的,而不是公有构造或者系统默认的公有构造方法。
二.代码实现
单例模式实现有好几种,我们这里一一介绍并对比之间的优劣:
2.1 饿汉式(静态常量法)
源码:
class Singleton{
//第一步:提供私有构造方法,外部不能new
private Singleton() {
}
//第二步:在类的内部创建方法
private final static Singleton instance = new Singleton();
//第三步:向外抛出一个静态的公有方法,用来获取instance实例
public static Singleton getInstance(){
return instance;
}
}
测试:
//测试
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1.hashCode());
System.out.println(singleton1.hashCode());
}
核心关键是提供静态构造函数并且类向外抛出一个静态公有方法用来获取对象实例。
总结:
-
优点:代码简单,在类加载个过程中完成实例化,避免了多线程同步等问题。
-
缺点:在类加载的过程中完成了实例化,如果程序始终没用到这个实例,那么就会浪费内存,即没有实现懒加载的效果。
-
所以这种方法是可用的,只是可能存在内存浪费的问题,如果确定程序会用到这个实例对象,那这种方法是完全可行的。
2.2 饿汉式(静态代码块法)
源码:
class Singleton{
//第一步:构造方法私有化
private Singleton(){
}
//第二步:创建对象实例
private static Singleton instance;
//第三步:静态代码块内创建单例对象
static {
instance = new Singleton();
}
//第四步:向外抛出一个静态的公有方法,用来获取instance实例
public static Singleton getInstance(){
return instance;
}
}
总结:
- 这种方法其实和上一种一样,只不过将实例化过程放在了静态代码内完成。
2.3 懒汉模式(第一种)线程不安全
源码:
class Singleton{
//第一步:构造器私有化
private Singleton(){
}
//第二步:创建对象实例
private static Singleton instance;
//第三步:对外抛出方法用来获取instance实例对象
public static Singleton getInstance(){
//判断instance是否已经创建,没有创建才创建
if (instance == null){
instance = new Singleton();
}
//如果已经创建,直接返回
return instance;
}
}
核心关键是提供静态构造函数并且类向外抛出一个静态公有方法用来获取对象实例,这种方法不是在类加载的时候就去创建实例,而是当第一次需要用到实例对象时,通过调用getInstance()来创建实例对象,实现了懒加载。
总结:
- 虽然起到了懒加载,但是线程不安全。
- 当多线程时,一个线程可能刚通过 if (instance == null)判断,但是还没有来得及new对象时,另一个线程便进行到了if (instance == null)判断,这时instance肯定还是null,所以这个线程也会去new新实例对象,从而产生多个实例。这种方法实际不会用到。
2.4 懒汉模式(第二种)线程安全
源码:
class Singleton{
//第一步:构造器私有化
private Singleton(){
}
//第二步:创建instance实例
private static Singleton instance;
//第三步:向外抛出公有方法,用来获取实例对象(加锁)
public static synchronized Singleton getInstance(){
//当instance为空时才去创建
if (instance == null){
instance = new Singleton();
}
//不为空直接返回
return instance;
}
}
核心关键是在上一种方法的基础上,对方法getInstance()加锁,用来保证线程安全
总结:
- 这种方法通过对方法的加锁,解决了上一种方法线程不安全的问题
- 但是这种方法因为是在方法上加锁,每个线程想要获得instance实例对象,就必须都得去同步。其实如果instance已经创建了,后序线程想要拿instance对象直接拿就可以了,而不用去同步完之后才能获得对象。所以实际开发中,对这种方法作了新的改进。
2.5 懒汉模式(第三种) 实际开发推荐使用
源码:
class Singleton {
//第一步:构造器私有化
private Singleton(){
}
//第二步:创建instance实例
private static Singleton instance;
//第三步:向外抛出公有静态方法,来获取instance实例对象
public static Singleton getInstance(){
if (instance == null){
synchronized (Singleton.class){
//双重检查,保证线程安全
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
测试代码:
//测试
public static void main(String[] args) {
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println("getInstance获取的instance对象:"+instance1.hashCode());
System.out.println("getInstance获取的instance对象:"+instance2.hashCode());
}
结果:
核心关键是双重检测
总结:
- 这种方法通过加锁以及双重检查实现高效率且线程安全。
- 双重检查在多线程实际开发中经常使用,来保证线程安全。
- 当instance实例对象创建之后,后序线程再要通过getInstance()获取实例对象时,因为instance已经不是null了,所以可以直接返回, 而不需要反复进行方法同步。
深究:这种方法难道真的是万无一失的吗?
1.通过反射来验证这种方法:
修改测试代码:
public static void main(String[] args) throws IOException, ClassNotFoundException {
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println("getInstance获取的instance对象:"+instance1.hashCode());
System.out.println("getInstance获取的instance对象:"+instance2.hashCode());
try {
//通过反射获取类构造器
Constructor<Singleton> declaredConstructor = Singleton.class.getDeclaredConstructor();
//获取到类的私有构造器(包括带有其他修饰符的构造器)
declaredConstructor.setAccessible(true);
//创建实例对象
Singleton singleton = declaredConstructor.newInstance();
System.out.println("反射创建的instance对象:"+singleton.hashCode());
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
结果:
由结果可以看出,通过反射拿到类的构造器去创建的实例对象与原来通过getInstance()获取的实例对象并不是同一个,两者的hashCode并不相同。
2.通过反反序列化来验证这种方法:
当然,要实现序列化,我们需要实现Serializable接口:
代码:
class Singleton implements Serializable {
//第一步:构造器私有化
private Singleton(){
}
//第二步:创建instance实例
private static Singleton instance;
//第三步:向外抛出公有静态方法,来获取instance实例对象
public static Singleton getInstance(){
if (instance == null){
synchronized (Singleton.class){
//双重检查,保证线程安全
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
测试代码:
①先序列化输出:
public static void main(String[] args) throws IOException, ClassNotFoundException {
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println("getInstance获取的instance对象:"+instance1.hashCode());
System.out.println("getInstance获取的instance对象:"+instance2.hashCode());
//测试序列化
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("testSerizlizable"));
os.writeObject(instance1);
os.close();
}
生成testSerizlizable文件:
②再反序列化获取实例对象:
public static void main(String[] args) throws IOException, ClassNotFoundException {
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println("getInstance获取的instance对象:"+instance1.hashCode());
System.out.println("getInstance获取的instance对象:"+instance2.hashCode());
//测试序列化
// ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("testSerizlizable"));
// os.writeObject(instance1);
// os.close();
ObjectInputStream is = new ObjectInputStream(new FileInputStream("testSerizlizable"));
Singleton instance3 = (Singleton) is.readObject();
System.out.println("反序列化获取的instance对象:"+instance3.hashCode());
}
运行结果:
由结果看出,反序列化后获得的实例对象与原来通过getInstance()获取的实例对象也不是同一个,两者的hashCode也不相同。
当然,针对反序列化,我们可以对代码进行一些改进去解决反序列化生成不同的实例对象:
改进代码:
class Singleton implements Serializable {
//添加一个版本号
static final long srrialVersionID = 42L;
//反序列化时也会生成一个版本号,与之前序列化时保存的版本号对比,
//若相同即表示同一个对象,若不同则报错
Object readResolve(){
return instance;
}
//第一步:构造器私有化
private Singleton(){
}
//第二步:创建instance实例
private static Singleton instance;
//第三步:向外抛出公有静态方法,来获取instance实例对象
public static Singleton getInstance(){
if (instance == null){
synchronized (Singleton.class){
//双重检查,保证线程安全
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
核心关键是提供一个版本号,反序列化时也会生成一个版本号,与之前序列化时保存的版本号对比,若相同即表示同一个对象,若不同则报错
再次序列化之后,反序列化结果:
由结果看出,反序列化后获得的实例对象与原来通过getInstance()获取的实例对象的hashCode相同。
2.6 静态内部类完成单例模式
源码:
class Singleton{
private static volatile Singleton instance;
//第二步:构造器私有化
private Singleton(){
}
//第三步:静态内部类,该类中有一个静态属性Singleton
private static class SingletonInstance{
private static final Singleton INSTANCE = new Singleton();
}
//第四步:提供静态的公有方法,返回SingletonInstance.INSTANCE
public static Singleton getInstance(){
return SingletonInstance.INSTANCE;
}
}
核心关键是静态内部类,该类中有一个静态属性Singleton
总结:
- 1.采用了类加载的机制保证初始化实例时只有一个线程。
- 2.这种方式在Singleon类加载的时候并不会立即实例化,而是当需要实例化instance时,通过调用getInstance方法,才会去装载静态内部类SingletonInstance,从而完成Singleton 的实例化。
- 3.类的静态属性只会在第一次加载类的时候初始化,所以这个方法是JVM帮我们实现了线程安全,在类进行初始化时,其他线程是进不来的。
2.7 枚举实现单例模式
源码:
enum Singleton{
INSTANCE;
public void helloWorld(){
System.out.println("hello world!");
}
}
测试:
public static void main(String[] args) {
Singleton instance1 = Singleton.INSTANCE;
Singleton instance2 = Singleton.INSTANCE;
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
instance1.helloWorld();
}
结果:
总结:
- 枚举方法可以说是实现单例模式最完美的方法。
- 可以防止反序列化重建新的对象,它存在自己的反序列化机制,而且不支持反射创建对应实例。
- 利用类加载机制,保存线程安全。
推荐使用!!!!!!!!!!!!!
原因:这种实现方式还没有被广泛采用,但这是实现单例模式的最佳方法。它更简洁,自动支持序列化机制,绝对防止多次实例化。这种方式是 Effective Java 作者 Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝对防止多次实例化。不过,由于 JDK1.5 之后才加入 enum 特性,用这种方式写不免让人感觉生疏,在实际工作中,也很少用。不能通过 reflection attack 即反射来调用私有构造方法。
当然,根据实际需求,可以灵活使用上述几种方法来实现单例模式。