汇总目录请点击访问:《设计模式目录汇总》 喜欢内容的话欢迎关注、点赞、收藏!感谢支持,祝大家祉猷并茂,顺遂无虞!
单例模式(Singleton Pattern)是一种创建型设计模式,旨在确保某个类只有一个实例,并提供一个全局访问点。
C++ 实现
#include <iostream>
#include <mutex>
class Singleton {
public:
// 禁用拷贝构造和赋值运算符
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
// 获取唯一实例
static Singleton& getInstance() {
static Singleton instance; // 使用C++11的magic static,线程安全
return instance;
}
void doSomething() {
std::cout << "Doing something in Singleton instance!" << std::endl;
}
private:
// 私有化构造函数
Singleton() {
std::cout << "Singleton initialized." << std::endl;
}
};
int main() {
Singleton& instance = Singleton::getInstance();
instance.doSomething();
return 0;
}
C# 实现
using System;
public sealed class Singleton {
private static readonly Lazy<Singleton> lazyInstance =
new Lazy<Singleton>(() => new Singleton());
// 私有化构造函数
private Singleton() {
Console.WriteLine("Singleton initialized.");
}
public static Singleton Instance => lazyInstance.Value;
public void DoSomething() {
Console.WriteLine("Doing something in Singleton instance!");
}
}
class Program {
static void Main(string[] args) {
Singleton instance = Singleton.Instance;
instance.DoSomething();
}
}
class Singleton {
public:
static Singleton& getInstance() {
return instance;
}
void doSomething() {}
private:
Singleton() {}
static Singleton instance; // 静态成员变量
};
// 初始化静态成员变量
Singleton Singleton::instance;
public sealed class Singleton {
private static readonly Singleton instance = new Singleton();
private Singleton() {}
public static Singleton Instance => instance;
}
#include <mutex>
class Singleton {
public:
static Singleton* getInstance() {
if (!instance) {
std::lock_guard<std::mutex> lock(mutex);
if (!instance) { // 双重检查锁
instance = new Singleton();
}
}
return instance;
}
void doSomething() {}
private:
Singleton() {}
static Singleton* instance;
static std::mutex mutex;
};
// 初始化静态成员
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mutex;
using System;
public sealed class Singleton {
private static Singleton instance;
private static readonly object lockObj = new object();
private Singleton() {}
public static Singleton Instance {
get {
if (instance == null) {
lock (lockObj) {
if (instance == null) { // 双重检查锁
instance = new Singleton();
}
}
}
return instance;
}
}
}
magic static
或 Lazy<T>
实现。C++11 的 magic static
:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
双重检查锁(DCL):
C# 的 Lazy<T>
:
private static readonly Lazy<Singleton> instance =
new Lazy<Singleton>(() => new Singleton());
依赖注入是一种设计模式,通过将类的依赖项通过构造函数、属性或方法传入,而不是类自己创建依赖对象。
特性 | 单例模式 | 依赖注入 |
---|---|---|
实例管理 | 由类自己控制实例的创建。 | 由容器管理实例的创建和生命周期。 |
耦合性 | 高耦合(类依赖自身实例)。 | 低耦合(外部控制依赖注入)。 |
使用场景 | 全局唯一实例场景。 | 灵活注入不同依赖的场景。 |
测试难度 | 难以单元测试(强依赖类内部实现)。 | 易于测试(可替换依赖实现)。 |
单例模式和依赖注入并不冲突,单例实例可以作为依赖注入的一部分:
容器管理单例实例:通过 DI 容器将单例模式封装,避免手动管理实例。
services.AddSingleton<Singleton>();
在 ASP.NET Core 中:
public interface ILoggerService {
void Log(string message);
}
public class SingletonLogger : ILoggerService {
public void Log(string message) {
Console.WriteLine($"Log: {message}");
}
}
// 注册单例
services.AddSingleton<ILoggerService, SingletonLogger>();
// 使用
public class SomeService {
private readonly ILoggerService _logger;
public SomeService(ILoggerService logger) {
_logger = logger;
}
public void DoWork() {
_logger.Log("Work in progress.");
}
}
欢迎关注、点赞、收藏!更多系列内容可以点击专栏目录订阅,感谢支持,再次祝大家祉猷并茂,顺遂无虞!
若将文章用作它处,请一定注明出处,商用请私信联系我!