一、Singleton 只有一个实例(单例模式)

程序在运行的过程中,通常会出现多个实例。

比如字符串中的 java.lang.String 类的实例与字符串是一一对应的关系,所以当有 1000 个字符串的时候,会生成 1000 个实例

但是,当我们的程序中某个东西只会存在一个时,就会有 “只创建一个实例” 的需求。

比如:

  1. 程序所运行的那台计算机的类
  2. 表示软件系统,相关设置的类
  3. 以及表示视窗系统(windows system)

我们要做到只调用一次 new MyClass(),就可以达到只生成一个实例的目的。这种只生成一个实例的模式称为 Singleton模式

二、示例程序

类名 功能
Singleton 只存在一个实例的类,提供 getInstance() 方法
Main 测试程序行为的类

2.1 饿汉模式

PS: 细分的话,单例模式还分场景(懒汉模式,恶汉模式)

  1. package singleton;
  2. /**
  3. * 单例模式的实现 (饿汉式)
  4. */
  5. public class Singleton {
  6. private static Singleton singleton = new Singleton();
  7. // 禁止从外部调用构造函数,为了保证只生成一个实例,就必须这么做
  8. // 防止使用 new 关键字,对构造方法设置 private
  9. private Singleton () {
  10. System.out.println("生成一个实例");
  11. }
  12. // 返回实例的 static 方法
  13. public static Singleton getInstance() {
  14. return singleton;
  15. }
  16. }

2.2 懒汉模式

  1. package singleton;
  2. /**
  3. * 懒汉式单例模式(线程不安全)
  4. */
  5. public class SingletonLazy {
  6. private static SingletonLazy singletonLazy = null;
  7. private SingletonLazy() {
  8. System.out.println("实例化了");
  9. }
  10. public static SingletonLazy getInstance() {
  11. if (singletonLazy == null) {
  12. singletonLazy = new SingletonLazy();
  13. }
  14. return singletonLazy;
  15. }
  16. }

2.3 枚举生成单例

  1. package singleton;
  2. public enum SingletonEnum {
  3. Singleton
  4. }

Main

  1. public static void main(String[] args) {
  2. System.out.println("Begin...");
  3. Singleton s1 = Singleton.getInstance();
  4. Singleton s2 = Singleton.getInstance();
  5. if (s1 == s2) {
  6. System.out.println("s1 和 s2 是相同的实例");
  7. } else {
  8. System.out.println("s1 和 s2 不是相同的实例");
  9. }
  10. System.out.println("End...");
  11. }

image.png

三、Singleton 模式登场的角色

  • Singleton 模式

在该模式中,只有这么一个角色,该角色有一个返回一个唯一实例的 static 方法,该方法总会返回同一个实例

四、在哪里我们用到了 Singleton

  1. 使用 Spring 框架创建 Bean 的时候,默认的 scope 就是 Bean