C++学习笔记-Singletons

单例模式(Singleton Pattern)是一种创建型设计模式,确保一个类只有一个实例,并提供全局访问点。在C++中,单例模式有多种实现方式,每种都有其优缺点和适用场景。

基本单例实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

class Random
{
public:
    Random(const Random&) = delete;

    static Random& GetInstance()
    {
        static Random instance;
        return instance;
    }

    /* 这样你可以直接Random::Float()的方式调用,而不需要调用GetInstance() */
    static float Float() { return GetInstance().FloatImpl(); }
    
private:
    Random() {};
    float FloatImpl() { return 0.5f; } // 模拟返回一个float随机数
};

void BasicSingletonDemo()
{
    std::cout << "=== Basic Singleton Demo ===" << std::endl;
    
    // Random instance = Random::GetInstance(); // 删除了拷贝构造函数,所以这么赋值会报错为拷贝赋值相当于拷贝了一个实例,这样就不是单例了。
    float value = Random::Float();
    std::cout << "Random value: " << value << std::endl;
    
    // 验证单例性质
    Random& instance1 = Random::GetInstance();
    Random& instance2 = Random::GetInstance();
    
    std::cout << "Instance1 address: " << &instance1 << std::endl;
    std::cout << "Instance2 address: " << &instance2 << std::endl;
    std::cout << "Same instance: " << (&instance1 == &instance2 ? "Yes" : "No") << std::endl;
}

int main()
{
    BasicSingletonDemo();
    return 0;
}

不同的单例实现方式

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#include <iostream>
#include <memory>
#include <mutex>

// 1. 懒汉式单例(线程不安全)
class LazySingleton
{
private:
    static LazySingleton* instance;
    LazySingleton() { std::cout << "LazySingleton created" << std::endl; }
    
public:
    static LazySingleton* GetInstance()
    {
        if (instance == nullptr)
        {
            instance = new LazySingleton();
        }
        return instance;
    }
    
    void DoSomething() { std::cout << "LazySingleton doing something" << std::endl; }
    
    // 注意:这个实现没有处理内存释放
};

LazySingleton* LazySingleton::instance = nullptr;

// 2. 饿汉式单例(线程安全)
class EagerSingleton
{
private:
    static EagerSingleton instance;
    EagerSingleton() { std::cout << "EagerSingleton created" << std::endl; }
    
public:
    static EagerSingleton& GetInstance()
    {
        return instance;
    }
    
    void DoSomething() { std::cout << "EagerSingleton doing something" << std::endl; }
};

EagerSingleton EagerSingleton::instance; // 程序启动时创建

// 3. 线程安全的懒汉式单例
class ThreadSafeSingleton
{
private:
    static ThreadSafeSingleton* instance;
    static std::mutex mutex_;
    ThreadSafeSingleton() { std::cout << "ThreadSafeSingleton created" << std::endl; }
    
public:
    static ThreadSafeSingleton* GetInstance()
    {
        std::lock_guard<std::mutex> lock(mutex_);
        if (instance == nullptr)
        {
            instance = new ThreadSafeSingleton();
        }
        return instance;
    }
    
    void DoSomething() { std::cout << "ThreadSafeSingleton doing something" << std::endl; }
};

ThreadSafeSingleton* ThreadSafeSingleton::instance = nullptr;
std::mutex ThreadSafeSingleton::mutex_;

// 4. 双重检查锁定(Double-Checked Locking)
class DoubleCheckedSingleton
{
private:
    static DoubleCheckedSingleton* instance;
    static std::mutex mutex_;
    DoubleCheckedSingleton() { std::cout << "DoubleCheckedSingleton created" << std::endl; }
    
public:
    static DoubleCheckedSingleton* GetInstance()
    {
        if (instance == nullptr)
        {
            std::lock_guard<std::mutex> lock(mutex_);
            if (instance == nullptr)
            {
                instance = new DoubleCheckedSingleton();
            }
        }
        return instance;
    }
    
    void DoSomething() { std::cout << "DoubleCheckedSingleton doing something" << std::endl; }
};

DoubleCheckedSingleton* DoubleCheckedSingleton::instance = nullptr;
std::mutex DoubleCheckedSingleton::mutex_;

// 5. Meyer's Singleton(推荐)
class MeyersSingleton
{
private:
    MeyersSingleton() { std::cout << "MeyersSingleton created" << std::endl; }
    
public:
    static MeyersSingleton& GetInstance()
    {
        static MeyersSingleton instance; // C++11保证线程安全
        return instance;
    }
    
    // 禁止拷贝和赋值
    MeyersSingleton(const MeyersSingleton&) = delete;
    MeyersSingleton& operator=(const MeyersSingleton&) = delete;
    
    void DoSomething() { std::cout << "MeyersSingleton doing something" << std::endl; }
};

// 6. 使用智能指针的单例
class SmartPtrSingleton
{
private:
    static std::unique_ptr<SmartPtrSingleton> instance;
    static std::once_flag initialized;
    SmartPtrSingleton() { std::cout << "SmartPtrSingleton created" << std::endl; }
    
public:
    static SmartPtrSingleton& GetInstance()
    {
        std::call_once(initialized, []() {
            instance = std::unique_ptr<SmartPtrSingleton>(new SmartPtrSingleton());
        });
        return *instance;
    }
    
    SmartPtrSingleton(const SmartPtrSingleton&) = delete;
    SmartPtrSingleton& operator=(const SmartPtrSingleton&) = delete;
    
    void DoSomething() { std::cout << "SmartPtrSingleton doing something" << std::endl; }
};

std::unique_ptr<SmartPtrSingleton> SmartPtrSingleton::instance = nullptr;
std::once_flag SmartPtrSingleton::initialized;

void SingletonImplementationsDemo()
{
    std::cout << "=== Singleton Implementations Demo ===" << std::endl;
    
    std::cout << "\n1. Lazy Singleton:" << std::endl;
    LazySingleton::GetInstance()->DoSomething();
    
    std::cout << "\n2. Eager Singleton:" << std::endl;
    EagerSingleton::GetInstance().DoSomething();
    
    std::cout << "\n3. Thread Safe Singleton:" << std::endl;
    ThreadSafeSingleton::GetInstance()->DoSomething();
    
    std::cout << "\n4. Double Checked Singleton:" << std::endl;
    DoubleCheckedSingleton::GetInstance()->DoSomething();
    
    std::cout << "\n5. Meyer's Singleton:" << std::endl;
    MeyersSingleton::GetInstance().DoSomething();
    
    std::cout << "\n6. Smart Pointer Singleton:" << std::endl;
    SmartPtrSingleton::GetInstance().DoSomething();
}

int main()
{
    SingletonImplementationsDemo();
    return 0;
}

实际应用场景

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <map>
#include <chrono>
#include <iomanip>
#include <sstream>

// 日志管理器单例
class Logger
{
public:
    enum class Level { DEBUG, INFO, WARNING, ERROR };
    
private:
    std::ofstream logFile;
    Level currentLevel;
    
    Logger() : currentLevel(Level::INFO)
    {
        logFile.open("application.log", std::ios::app);
    }
    
public:
    static Logger& GetInstance()
    {
        static Logger instance;
        return instance;
    }
    
    Logger(const Logger&) = delete;
    Logger& operator=(const Logger&) = delete;
    
    ~Logger()
    {
        if (logFile.is_open())
        {
            logFile.close();
        }
    }
    
    void SetLevel(Level level) { currentLevel = level; }
    
    void Log(Level level, const std::string& message)
    {
        if (level >= currentLevel)
        {
            auto now = std::chrono::system_clock::now();
            auto time_t = std::chrono::system_clock::to_time_t(now);
            
            std::stringstream ss;
            ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
            
            std::string levelStr = LevelToString(level);
            std::string logEntry = "[" + ss.str() + "] " + levelStr + ": " + message;
            
            std::cout << logEntry << std::endl;
            if (logFile.is_open())
            {
                logFile << logEntry << std::endl;
                logFile.flush();
            }
        }
    }
    
    void Debug(const std::string& message) { Log(Level::DEBUG, message); }
    void Info(const std::string& message) { Log(Level::INFO, message); }
    void Warning(const std::string& message) { Log(Level::WARNING, message); }
    void Error(const std::string& message) { Log(Level::ERROR, message); }
    
private:
    std::string LevelToString(Level level)
    {
        switch (level)
        {
            case Level::DEBUG: return "DEBUG";
            case Level::INFO: return "INFO";
            case Level::WARNING: return "WARNING";
            case Level::ERROR: return "ERROR";
            default: return "UNKNOWN";
        }
    }
};

// 配置管理器单例
class ConfigManager
{
private:
    std::map<std::string, std::string> config;
    
    ConfigManager()
    {
        LoadConfig();
    }
    
    void LoadConfig()
    {
        // 模拟从文件加载配置
        config["database_host"] = "localhost";
        config["database_port"] = "5432";
        config["max_connections"] = "100";
        config["log_level"] = "INFO";
        config["cache_size"] = "1024";
    }
    
public:
    static ConfigManager& GetInstance()
    {
        static ConfigManager instance;
        return instance;
    }
    
    ConfigManager(const ConfigManager&) = delete;
    ConfigManager& operator=(const ConfigManager&) = delete;
    
    std::string GetString(const std::string& key, const std::string& defaultValue = "")
    {
        auto it = config.find(key);
        return (it != config.end()) ? it->second : defaultValue;
    }
    
    int GetInt(const std::string& key, int defaultValue = 0)
    {
        auto value = GetString(key);
        return value.empty() ? defaultValue : std::stoi(value);
    }
    
    void SetString(const std::string& key, const std::string& value)
    {
        config[key] = value;
    }
    
    void SetInt(const std::string& key, int value)
    {
        config[key] = std::to_string(value);
    }
    
    void PrintAll()
    {
        std::cout << "Configuration:" << std::endl;
        for (const auto& [key, value] : config)
        {
            std::cout << "  " << key << " = " << value << std::endl;
        }
    }
};

// 数据库连接池单例
class DatabasePool
{
private:
    std::vector<std::string> availableConnections;
    std::vector<std::string> usedConnections;
    int maxConnections;
    
    DatabasePool()
    {
        maxConnections = ConfigManager::GetInstance().GetInt("max_connections", 10);
        InitializePool();
    }
    
    void InitializePool()
    {
        for (int i = 0; i < maxConnections; ++i)
        {
            availableConnections.push_back("Connection_" + std::to_string(i));
        }
        Logger::GetInstance().Info("Database pool initialized with " + std::to_string(maxConnections) + " connections");
    }
    
public:
    static DatabasePool& GetInstance()
    {
        static DatabasePool instance;
        return instance;
    }
    
    DatabasePool(const DatabasePool&) = delete;
    DatabasePool& operator=(const DatabasePool&) = delete;
    
    std::string GetConnection()
    {
        if (availableConnections.empty())
        {
            Logger::GetInstance().Warning("No available database connections");
            return "";
        }
        
        std::string connection = availableConnections.back();
        availableConnections.pop_back();
        usedConnections.push_back(connection);
        
        Logger::GetInstance().Debug("Acquired connection: " + connection);
        return connection;
    }
    
    void ReleaseConnection(const std::string& connection)
    {
        auto it = std::find(usedConnections.begin(), usedConnections.end(), connection);
        if (it != usedConnections.end())
        {
            usedConnections.erase(it);
            availableConnections.push_back(connection);
            Logger::GetInstance().Debug("Released connection: " + connection);
        }
    }
    
    void PrintStatus()
    {
        std::cout << "Database Pool Status:" << std::endl;
        std::cout << "  Available: " << availableConnections.size() << std::endl;
        std::cout << "  In use: " << usedConnections.size() << std::endl;
        std::cout << "  Total: " << maxConnections << std::endl;
    }
};

// 缓存管理器单例
template<typename Key, typename Value>
class CacheManager
{
private:
    std::map<Key, Value> cache;
    size_t maxSize;
    
    CacheManager()
    {
        maxSize = ConfigManager::GetInstance().GetInt("cache_size", 100);
    }
    
public:
    static CacheManager& GetInstance()
    {
        static CacheManager instance;
        return instance;
    }
    
    CacheManager(const CacheManager&) = delete;
    CacheManager& operator=(const CacheManager&) = delete;
    
    void Put(const Key& key, const Value& value)
    {
        if (cache.size() >= maxSize)
        {
            // 简单的LRU:删除第一个元素
            cache.erase(cache.begin());
        }
        cache[key] = value;
        Logger::GetInstance().Debug("Cache put: key added");
    }
    
    bool Get(const Key& key, Value& value)
    {
        auto it = cache.find(key);
        if (it != cache.end())
        {
            value = it->second;
            Logger::GetInstance().Debug("Cache hit: key found");
            return true;
        }
        Logger::GetInstance().Debug("Cache miss: key not found");
        return false;
    }
    
    void Clear()
    {
        cache.clear();
        Logger::GetInstance().Info("Cache cleared");
    }
    
    size_t Size() const { return cache.size(); }
    size_t MaxSize() const { return maxSize; }
};

void PracticalApplicationsDemo()
{
    std::cout << "=== Practical Applications Demo ===" << std::endl;
    
    // 配置管理
    std::cout << "\n1. Configuration Manager:" << std::endl;
    auto& config = ConfigManager::GetInstance();
    config.PrintAll();
    
    // 日志管理
    std::cout << "\n2. Logger:" << std::endl;
    auto& logger = Logger::GetInstance();
    logger.SetLevel(Logger::Level::DEBUG);
    logger.Info("Application started");
    logger.Debug("Debug information");
    logger.Warning("This is a warning");
    logger.Error("An error occurred");
    
    // 数据库连接池
    std::cout << "\n3. Database Pool:" << std::endl;
    auto& dbPool = DatabasePool::GetInstance();
    dbPool.PrintStatus();
    
    auto conn1 = dbPool.GetConnection();
    auto conn2 = dbPool.GetConnection();
    dbPool.PrintStatus();
    
    dbPool.ReleaseConnection(conn1);
    dbPool.PrintStatus();
    
    // 缓存管理
    std::cout << "\n4. Cache Manager:" << std::endl;
    auto& cache = CacheManager<std::string, std::string>::GetInstance();
    
    cache.Put("user:123", "John Doe");
    cache.Put("user:456", "Jane Smith");
    
    std::string value;
    if (cache.Get("user:123", value))
    {
        std::cout << "Found in cache: " << value << std::endl;
    }
    
    if (!cache.Get("user:789", value))
    {
        std::cout << "Not found in cache: user:789" << std::endl;
    }
    
    std::cout << "Cache size: " << cache.Size() << "/" << cache.MaxSize() << std::endl;
}

int main()
{
    PracticalApplicationsDemo();
    return 0;
}

单例模式的优缺点和替代方案

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#include <iostream>
#include <memory>
#include <functional>

// 单例的问题演示
class ProblematicSingleton
{
private:
    static int instanceCount;
    
public:
    ProblematicSingleton() { instanceCount++; }
    static ProblematicSingleton& GetInstance()
    {
        static ProblematicSingleton instance;
        return instance;
    }
    
    static int GetInstanceCount() { return instanceCount; }
    void DoSomething() { std::cout << "Doing something..." << std::endl; }
};

int ProblematicSingleton::instanceCount = 0;

// 替代方案1:依赖注入
class Service
{
public:
    virtual ~Service() = default;
    virtual void DoWork() = 0;
};

class ConcreteService : public Service
{
public:
    void DoWork() override
    {
        std::cout << "ConcreteService doing work" << std::endl;
    }
};

class Client
{
private:
    std::shared_ptr<Service> service;
    
public:
    Client(std::shared_ptr<Service> svc) : service(svc) {}
    
    void Execute()
    {
        service->DoWork();
    }
};

// 替代方案2:静态类
class StaticUtility
{
public:
    static void DoUtilityWork()
    {
        std::cout << "Static utility doing work" << std::endl;
    }
    
    static int Calculate(int a, int b)
    {
        return a + b;
    }
    
private:
    StaticUtility() = delete; // 禁止实例化
};

// 替代方案3:命名空间
namespace UtilityNamespace
{
    void DoWork()
    {
        std::cout << "Namespace utility doing work" << std::endl;
    }
    
    int Calculate(int a, int b)
    {
        return a * b;
    }
}

// 替代方案4:工厂模式
class Factory
{
public:
    static std::unique_ptr<Service> CreateService()
    {
        return std::make_unique<ConcreteService>();
    }
};

// 替代方案5:全局对象(谨慎使用)
class GlobalService
{
public:
    void DoWork() { std::cout << "Global service doing work" << std::endl; }
};

GlobalService g_globalService; // 全局实例

void SingletonProblemsDemo()
{
    std::cout << "=== Singleton Problems Demo ===" << std::endl;
    
    std::cout << "Singleton problems:" << std::endl;
    std::cout << "1. Global state - makes testing difficult" << std::endl;
    std::cout << "2. Hidden dependencies - not clear from function signatures" << std::endl;
    std::cout << "3. Tight coupling - hard to replace or mock" << std::endl;
    std::cout << "4. Thread safety concerns" << std::endl;
    std::cout << "5. Destruction order issues" << std::endl;
    std::cout << "6. Violates Single Responsibility Principle" << std::endl;
    
    // 演示隐藏依赖问题
    auto& singleton = ProblematicSingleton::GetInstance();
    singleton.DoSomething(); // 不清楚这个函数依赖什么
}

void AlternativesDemo()
{
    std::cout << "\n=== Alternatives Demo ===" << std::endl;
    
    // 1. 依赖注入
    std::cout << "1. Dependency Injection:" << std::endl;
    auto service = std::make_shared<ConcreteService>();
    Client client(service);
    client.Execute(); // 依赖关系明确
    
    // 2. 静态类
    std::cout << "\n2. Static Class:" << std::endl;
    StaticUtility::DoUtilityWork();
    int result = StaticUtility::Calculate(5, 3);
    std::cout << "Static calculation result: " << result << std::endl;
    
    // 3. 命名空间
    std::cout << "\n3. Namespace:" << std::endl;
    UtilityNamespace::DoWork();
    int result2 = UtilityNamespace::Calculate(5, 3);
    std::cout << "Namespace calculation result: " << result2 << std::endl;
    
    // 4. 工厂模式
    std::cout << "\n4. Factory Pattern:" << std::endl;
    auto factoryService = Factory::CreateService();
    factoryService->DoWork();
    
    // 5. 全局对象
    std::cout << "\n5. Global Object:" << std::endl;
    g_globalService.DoWork();
}

// 何时使用单例的指导原则
void SingletonGuidelinesDemo()
{
    std::cout << "\n=== Singleton Guidelines ===" << std::endl;
    
    std::cout << "When to use Singleton:" << std::endl;
    std::cout << "1. Truly need only one instance (e.g., hardware interface)" << std::endl;
    std::cout << "2. Global access point is necessary" << std::endl;
    std::cout << "3. Lazy initialization is important" << std::endl;
    std::cout << "4. Thread safety is handled properly" << std::endl;
    
    std::cout << "\nWhen NOT to use Singleton:" << std::endl;
    std::cout << "1. Just for convenience (use dependency injection)" << std::endl;
    std::cout << "2. When you need multiple instances in tests" << std::endl;
    std::cout << "3. When the class has multiple responsibilities" << std::endl;
    std::cout << "4. When global state is not actually needed" << std::endl;
    
    std::cout << "\nBetter alternatives:" << std::endl;
    std::cout << "1. Dependency injection for testability" << std::endl;
    std::cout << "2. Static functions for stateless utilities" << std::endl;
    std::cout << "3. Factory pattern for object creation" << std::endl;
    std::cout << "4. Service locator pattern for service discovery" << std::endl;
}

int main()
{
    SingletonProblemsDemo();
    AlternativesDemo();
    SingletonGuidelinesDemo();
    
    return 0;
}

总结

  1. 单例模式基础:确保类只有一个实例并提供全局访问点
  2. 实现方式
    • 懒汉式:需要时才创建(需考虑线程安全)
    • 饿汉式:程序启动时创建(天然线程安全)
    • Meyer's单例:推荐方式(C++11保证线程安全)
    • 双重检查锁定:性能优化但复杂
  3. 实际应用
    • 日志管理器
    • 配置管理器
    • 数据库连接池
    • 缓存管理器
  4. 优点
    • 控制实例数量
    • 全局访问点
    • 延迟初始化
    • 节省内存
  5. 缺点
    • 全局状态难以测试
    • 隐藏依赖关系
    • 紧耦合
    • 线程安全复杂性
  6. 替代方案
    • 依赖注入(推荐)
    • 静态类/函数
    • 命名空间
    • 工厂模式
    • 全局对象
  7. 最佳实践
    • 谨慎使用,优先考虑依赖注入
    • 使用Meyer's单例实现
    • 禁止拷贝和赋值
    • 考虑线程安全
    • 明确生命周期管理
updatedupdated2025-09-202025-09-20