一个单一的类,负责创建自己的对象,同时确保系统中只有单个对象被创建
单例特点
- 某个类只能有一个实例;(构造器私有)
- 它必须自行创建这个实例;(自己编写实例化逻辑)
它必须自行向整个系统提供这个实例;(对外提供实例化方法)
饿汉式
public class Runtime { private static final Runtime currentRuntime = new Runtime(); public static Runtime getRuntime() { return currentRuntime; } /** Don't let anyone else instantiate this class */ private Runtime() {}}
懒汉式
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;}
应用场景
- 多线程中的线程池
- 数据库的连接池
- 系统环境信息
- 上下文(ServletContext)