Fork me on GitHub

设计模式(4)

创造型模式-单例模式

介绍

保证一个类仅有一个实例,并提供一个访问它的全局访问点

实例

  • 创建Singleton
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public class SingleObject {

    //创建 SingleObject 的一个对象
    private static SingleObject instance = new SingleObject();

    //让构造函数为 private,这样该类就不会被实例化
    private SingleObject(){}

    //获取唯一可用的对象
    public static SingleObject getInstance(){
    return instance;
    }

    public void showMessage(){
    System.out.println("Hello World!");
    }
    }
  • singleton类获取唯一的对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public class SingletonPatternDemo {
    public static void main(String[] args) {

    //不合法的构造函数
    //编译时错误:构造函数 SingleObject() 是不可见的
    //SingleObject object = new SingleObject();

    //获取唯一可用的对象
    SingleObject object = SingleObject.getInstance();

    //显示消息
    object.showMessage();
    }
    }
  • 输出结果

    1
    Hello World!

懒汉式(线程不安全)

1
2
3
4
5
6
7
8
9
10
11
public class Singleton {  
private static Singleton instance;
private Singleton (){}

public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

懒汉式(线程安全)

1
2
3
4
5
6
7
8
9
10
public class Singleton {  
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

饿汉式

1
2
3
4
5
6
7
public class Singleton {  
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}

双重检验锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton {  
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}

静态内部类

1
2
3
4
5
6
7
8
9
public class Singleton {  
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}

枚举

1
2
3
4
5
public enum Singleton {  
INSTANCE;
public void whateverMethod() {
}
}

总结

保证一个类仅有一个实例,并提供一个访问它的全局访问点。
不建议使用懒汉式,建议使用饿汉式

参考

可以一读
菜鸟教程