原版设计模式之单例模式

Intent (定义)

Ensure a class only has one instance, and provide a global point of access to it.(确保一个类只有一个实例,并提供全局访问的通道)

Motivation (案例)

How do we ensure that a class has only one instance and that the instance is easily accessible?(如何确保一个类只有一个实例,并且是易于访问的?)
A global variable makes an object accessible, but it doesn’t keep you from instantiating multiple objects.(全局变量是可访问的,但是它不能阻止你实例化多个对象)
A better solution is to make the class itself responsible for keeping track of its sole instance. (好一点的解决方式是让类本身负责跟踪它唯一的实例【让类自己创建实例】)
The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. (这个类必须要确保,不能创建多个实例,同时要提供一个访问实例对象的方式)
This is the Singleton pattern.(这就是单例模式)

Applicability (适用点)

  • there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. (类必须只有一个实例,必须给客户端提供一个可访问实例的通道)
  • when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.(这个唯一的实例应当可以被子类扩展,同时客户端使用扩展的实例时无需修改过多的代码)

Structure (结构图)

在这里插入图片描述

Participants (类说明)

  • Singleton (单例)
    • defines an Instance operation that lets clients access its unique instance. Instance is a class operation (that is, a class method in Smalltalk and a static member function in C++). (定义一个实例化的操作,使客户端可以获取它唯一的实例对象,实例化是类的一个操作。)
    • may be responsible for creating its own unique instance. (可以自己创建唯一的实例)

Collaborations (约定)

Clients access a Singleton instance solely through Singleton’s Instance operation.(客户端通过单例的实例化操作访问它唯一的实例对象)

Related Patterns (相关模式)

Many patterns can be implemented using the Singleton pattern. See Abstract Factory (99), Builder (110), and Prototype (133).(许多模式都可以用单例模式实现,参考抽象工厂,建造者模式,和原型模式)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值