0%

设计模式 - 创建型 - 单例模式

类型 Type

  • 创建型 Creational

含义 Intent

The intent of the singleton pattern is to ensure that a class only has one instance, and to provide a global point of access to it.

例子 Real Example

Logger,通常来说应用中只会有一个,以避免意想不到的结果。

代码 Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Logger
{
private static readonly Lazy<Logger> lazyLogger = new Lazy<Logger>(() => new Logger());

public static Logger Instance => lazyLogger.Value;

protected Logger()
{
}

// <summary>
// SingletonOperation
// </summary>
public void Log(string message)
{
Console.WriteLine($"Log: {message}");
}
}

使用时机 Time to Use

  • When 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

用例 User Case

  • 管理数据库连接池 connection pool

  • 缓存 cache

  • 管理应用配置 manage application configuration

  • 通用资源管理 general resource management

模式好坏 Pattern Consequence

  • 违反了单一职责 Violates the SRP

    • 负责对象的创建 Control Creation

    • 负责对象的生命周期管理 manage own lifecycle

  • 严格的控制客户对其的访问 Strict Control over how and when clients access it

  • Avoids polluting the namespace with global variables

  • Subclassing allows configuring the application with an instance of the class you need at runtime

  • Multipe instances can be allowed without having to alter the client

  • 很多时候我们不用自己实现,让 IoC 容器管理吧