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;
}
|