较优秀的三种单例设计模式
前面我们介绍过饿汉式两种设计模式、懒汉式三种设计模式,都各有利弊,单例设计模式还有较为优秀的DoubleCheck(双重检查)、静态内部类、枚举方式实现的设计模式。
以下是它们的实现代码和分析
DoubleCheck(双重检查)
package com.design_patterns.singleton;
/**
* DoubleCheck双重检查实现单例模式
* 线程安全,效率高效,推荐使用
*/
class Person06{
private static volatile Person06 person = null; //声明Person06类的对象person
private Person06(){} //构造方法私有化
/**
* 通过双重检查的方式保证线程安全,提高运行效率,完美完成了单例模式的设计
* @return
*/
public static Person06 getInstance(){
if(person == null){ //检查person对象是否为null
synchronized (Person06.class){ //同步代码块
if(person == null){ //如果person对象为null
person = new Person06(); //对person对象进行实例化,
// 由于person使用volatile关键字声明,内容会立刻在内存中改变
}
}
}
return person; //返回person对象
}
}
public class SingletonType06 {
public static void main(String[] args) {
Person06 person = Person06.getInstance(); //根据Person04类中的静态方法获取实例
Person06 person06 = Person06.getInstance();
System.out.println("主线程Person06类的对象person是:\n" + person + "\n" + person.hashCode());
System.out.println("主线程Person06类的对象person06是:\n" + person + "\n" + person.hashCode());
System.out.println("这两个对象一样么?" + (person == person06));
}
}
运行结果
主线程Person06类的对象person是:
com.design_patterns.singleton.Person06@4554617c
1163157884
主线程Person06类的对象person06是:
com.design_patterns.singleton.Person06@4554617c
1163157884
这两个对象一样么?true
设计模式分析
静态内部类
package com.design_patterns.singleton;
/**
* 使用静态内部类实现单例模式
* 静态内部类在被调用时只会装载一次,而且线程安全
*/
class Person07{
private Person07(){} //进行构造方法私有化
public static class Person07Instance{ //定义静态内部类
private static final Person07 person = new Person07(); //定义Person07类对象person常量并进行实例化
}
public static Person07 getInstance(){ //获取对象的方法
return Person07Instance.person;
}
}
//测试类
public class SingletonType07 {
public static void main(String[] args) {
Person07 person = Person07.getInstance(); //根据Person04类中的静态方法获取实例
Person07 person07 = Person07.getInstance();
System.out.println("主线程Person07类的对象person是:\n" + person + "\n" + person.hashCode());
System.out.println("主线程Person07类的对象person07是:\n" + person + "\n" + person.hashCode());
System.out.println("这两个对象一样么?" + (person == person07));
}
}
运行结果
主线程Person07类的对象person是:
com.design_patterns.singleton.Person07@4554617c
1163157884
主线程Person07类的对象person07是:
com.design_patterns.singleton.Person07@4554617c
1163157884
这两个对象一样么?true
设计模式分析
枚举方式
package com.design_patterns.singleton;
/**
* 使用枚举类设计单例模式
*/
enum Person08{
INSTANCE;
}
public class SingletonType08 {
public static void main(String[] args) {
Person08 person = Person08.INSTANCE; //根据枚举获取单例对象
Person08 person08 = Person08.INSTANCE;
System.out.println("主线程Person07类的对象person是:\n" + person + "\n" + person.hashCode());
System.out.println("主线程Person07类的对象person07是:\n" + person + "\n" + person.hashCode());
System.out.println("这两个对象一样么?" + (person == person08));
}
}
运行结果
主线程Person07类的对象person是:
INSTANCE
1163157884
主线程Person07类的对象person07是:
INSTANCE
1163157884
这两个对象一样么?true
设计模式分析