保证全局只有一个实例。C++11 起最简洁的写法(线程安全):
class Logger {
public:
static Logger& instance() {
static Logger inst; // 局部静态变量,C++11 保证线程安全
return inst;
}
void log(const std::string& s) { ... }
private:
Logger() = default;
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
};
Logger::instance().log("hello");
把对象创建逻辑集中,调用方不关心具体类型:
struct IShape { virtual void draw() = 0; virtual ~IShape() {} };
struct Circle : IShape { void draw() override {} };
struct Square : IShape { void draw() override {} };
std::unique_ptr<IShape> createShape(const std::string& type) {
if (type == "circle") return std::make_unique<Circle>();
if (type == "square") return std::make_unique<Square>();
return nullptr;
}
一个对象状态变化时通知多个订阅者:
class Subject {
std::vector<std::function<void(int)>> observers;
public:
void subscribe(std::function<void(int)> fn) { observers.push_back(fn); }
void notify(int val) {
for (auto& fn : observers) fn(val);
}
};
Subject s;
s.subscribe([](int v){ std::cout << "收到: " << v; });
s.notify(42);
提示:设计模式解决的是"变化点"问题,别为模式而模式。优先用 std::function 回调替代复杂模式。