【图解设计模式系列】The Singleton Pattern: 单例模式
单例模式主要作用是保证在应用程序中,一个类只会有一个实例存在。典型的应用场景,比如文件系统建立目录,或数据库连接都需要这样的单例。实现单例模式常用的几种方式有饿汉式、懒汉式、懒汉双检索式、内部类实现式、枚举实现式等。
看完这个定义 仍然不知道到底是什么意思。
英文解释
ensures a class has only one instance, and provides a global point of access to it.

The above solution has multithreading issues. We have 3 ways to avoid multithreading issues (P180-P182):
- Add ‘synchronized’ to getInstance.
- Use eagerly created instance rather than a lazily created one.
- Use “double-checked locking” to reduce the use of synchronization in getInstance.
饿汉式(线程安全)
懒汉式(线程不安全)
代码太多 就不一一列举了。
实例中的实例
JDK的Runtime类就是用饿汉式单例模式实现的
public class Runtime {
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
}

浙公网安备 33010602011771号