Java设计模式之单例模式
所谓类的单例设计模式,就是采取一定的方法保证在整个软件系统中,对于某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。
单例模式有8种
饿汉式(静态常量)
JDK中,java.lang.Runtime源码就是采用这种单例模式。
class Singleton{
// 1.构造器私有化(防止外部 new对象)
private Singleton(){
}
// 2.类的内部创建对象
private final static Singleton instance = new Singleton();
// 3.向外暴露一个静态的公共方法。getInstance
public static Singleton getInstance(){
return instance;
}
}
优缺点:
- 优点:写法简单,在类装载的时候就完成实例化,避免了线程同步的问题。
- 缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从未使用过这个实例,则会造成内存浪费。
饿汉式(静态代码块)
class Singleton2{
// 1.构造器私有化(防止外部 new对象)
private Singleton2(){
}
// 2.类的内部创建对象
private static Singleton2 instance;
static {
instance = new Singleton2();
}
// 3.向外暴露一个静态的公共方法。getInstance
public static Singleton2 getInstance(){
return instance;
}
}
优缺点同静态常量。
懒汉式(线程不安全)
class Singleton3{
private static Singleton3 instance;
private Singleton3(){
}
public static Singleton3 getInstance(){
if (instance == null){
instance = new Singleton3();
}
return instance;
}
}
优缺点:
- 起到了懒加载的效果,但是只能在单线程下使用。
- 如果在多线程下,一个线程进入了if(instance == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可使用这种方式。
懒汉式(线程安全,同步方法)
class Singleton4{
private static Singleton4 instance;
private Singleton4(){
}
public static synchronized Singleton4 getInstance(){
if (instance == null){
instance = new Singleton4();
}
return instance;
}
}
优缺点:
- 解决了线程不安全的问题
- 效率太低,每个线程想获得类的实例时,执行getInstance()方法都要进行同步。而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例直接return就行了。方法进行同步效率太低。
懒汉式(同步代码块)
错误写法,不展示。
双重检查
class Singleton6{
private static volatile Singleton6 instance;
private Singleton6(){}
//提供一个静态的公有方法,加入双重检查代码,解决线程安全问题,同时解决懒加载问题。
public static Singleton6 getInstance(){
if (instance == null){
synchronized (Singleton6.class){
if (instance == null){
instance = new Singleton6();
}
}
}
return instance;
}
}
优缺点:
- Double-Check概念是多线程开发中常使用到的,如代码中所示,我们进行了两次if(instance == null)检查,这样就可以保证线程安全了。
- 线程安全,懒加载,效率较高。
静态内部类
class Singleton7 {
private Singleton7(){}
//静态内部类,该类中有一个静态属性Singleton7
//静态内部类调用时才会装载,JVM装载是线程安全的过程。
private static class SingletonInstance{
private static final Singleton7 instance = new Singleton7();
}
public static Singleton7 getInstance(){
return SingletonInstance.instance;
}
}
优缺点:
- 采用了类装载机制来保证初始化实例时只有一个线程。
- 静态内部类方式在Singleton7类被装载时,并不会立即实例化,而是在需要实例化时调用getInstance()才会装载SingletonInstance类,从而完成Singleton7的实例化。
- 类的静态属性只会在第一次加载类的时候初始化,JVM保证了线程的安全性。
- 线程安全,懒加载,效率高。
枚举
enum Singleton8 {
INSTANCE;
public void sayOK(){
System.out.println("OK");
}
}
public class Singleton8Demo{
public static void main(String[] args){
Singleton8 instance = Singleton8.INSTANCE;
Singleton8 instance2 = Singleton8.INSTANCE;
System.out.println(instance == instance2);
}
}
优缺点:
借助JDK1.5中添加的枚举类来实现单例模式,不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象,防止反射,推荐使用。

浙公网安备 33010602011771号