设计模式——单例模式

概念

单例模式(Singleton Pattern):确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。单例模式是一种对象创建型模式

对象创建型模式:专注于对象的实例化和创建过程。它们提供了一种创建对象的方式,以使系统更加灵活和具有扩展性

要点

  • 某个类只能有一个实例;
  • 它必须自行创建这个实例;
  • 它必须自行向整个系统提供这个实例

主要优点

(1)单例模式提供了对唯一实例的受控访问。因为单例类封装了它的唯一实例,所以它可以严格控制客户怎样以及何时访问它。
(2)由于在系统内存中只存在一个对象,因此可以节约系统资源。对于一些需要频繁创建和销毁的对象,单例模式无疑可以提高系统的性能。
(3)允许可变数目的实例。基于单例模式,开发人员可以进行扩展,使用与控制单例对象相似的方法来获得指定个数的实例对象,既节省系统资源,又解决了由于单例对象共享过多有损性能的问题。

主要缺点

(1)单例模式提供了对唯一实例的受控访问
(2)由于在系统内存中只存在一个对象,对于一些需要频繁创建和销毁的对象,单例模式无疑可以提高系统的性能。
(3)允许可变数目的实例。

适用场景

(1)系统只需要一个实例对象。
(2)客户调用类的单个实例只允许使用一个公共访问点。除了该公共访问点,不能通过其他途径访问该实例

javascript 实现代码

const Singleton = (function() {
   
  let instance;

  function createInstance() {
   
    // 在这里可以放一些初始化逻辑
    return {
   
      someMethod: function() {
   
        // 添加单例的方法和逻辑
      }
    };
  }

  return {
   
    getInstance: function() {
   
      if (!instance) {
   
        instance = createInstance();
      }
      return instance;
    }
  };
})();

// 使用单例
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // 输出 true,因为它们是同一个实例

typescript 实现代码

class Singleton {
   
  private static instance: Singleton | null = null;

  private constructor() {
   
    // 这里可以放一些初始化逻辑
  }

  public static getInstance(): Singleton {
   
    if (!Singleton.instance) {
   
      Singleton.instance = new Proxy(new Singleton(), {
   
        get: function(target, prop, receiver) {
   
          if (prop === 'instance') {
   
            return undefined; // 防止通过 instance 直接访问实例
          }
          return Reflect.get(target, prop, receiver);
        }
      });
    }
    return Singleton.instance as Singleton;
  }

  public someMethod() {
   
    // 在这里添加单例的方法和逻辑
  }
}

// 使用单例
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // 输出 true,因为它们是同一个实例

C# 实现

public class Singleton
{
   
    private static Singleton instance;
    private static readonly object lockObj = new object();

    private Singleton() {
    }

    public static Singleton GetInstance()
    {
   
        if (instance == null)
        {
   
            lock (lockObj)
            {
   
                if (instance == null)
                {
   
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

java实现代码

public class Singleton {
   
    private volatile static Singleton instance;

    private Singleton() {
   }

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

python 实现代码

def singleton(cls):
    instances = {
   }

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance

@singleton
class SingletonClass:
    def __init__(self, value):
        self.value = value

# 使用单例类
instance1 = SingletonClass(10)
instance2 = SingletonClass(20)

print(instance1.value)  # 输出:10
print(instance2.value)  # 输出:10,因为使用的是同一个实例

相关推荐

  1. 设计模式

    2023-12-19 07:08:01       63 阅读
  2. 设计模式

    2023-12-19 07:08:01       42 阅读
  3. 设计模式

    2023-12-19 07:08:01       40 阅读
  4. 设计模式

    2023-12-19 07:08:01       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-19 07:08:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-19 07:08:01       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-19 07:08:01       82 阅读
  4. Python语言-面向对象

    2023-12-19 07:08:01       91 阅读

热门阅读

  1. 云原生周刊:Kubernetes v1.29 正式发布 | 2023.12.18

    2023-12-19 07:08:01       68 阅读
  2. Linux网络配置命令

    2023-12-19 07:08:01       61 阅读
  3. 正则表达式零宽断言

    2023-12-19 07:08:01       53 阅读
  4. 鸿蒙OS应用开发之正则表达式检查

    2023-12-19 07:08:01       60 阅读
  5. 静态独享专线IP怎么设置?使用静态IP怎么上网

    2023-12-19 07:08:01       73 阅读
  6. 金和OA jc6 clobfield SQL注入漏洞复现

    2023-12-19 07:08:01       118 阅读
  7. 低成本SDR平台的构成与开发

    2023-12-19 07:08:01       70 阅读
  8. Redis 实现全局唯一ID

    2023-12-19 07:08:01       58 阅读
  9. 基于RBAC的k8s集群权限管控案例

    2023-12-19 07:08:01       50 阅读
  10. 【期末复习向】文本理解与数据挖掘-名词解释

    2023-12-19 07:08:01       60 阅读
  11. SGML .HTML 、XML和XHTML的区别?

    2023-12-19 07:08:01       59 阅读