《C++ Cookbook》是一本關于C++編程的實用指南,其中包含了許多設計模式的實現方法
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() {}
};
class Product {
public:
virtual void use() = 0;
};
class ConcreteProductA : public Product {
public:
void use() override {
// ...
}
};
class ConcreteProductB : public Product {
public:
void use() override {
// ...
}
};
class Factory {
public:
virtual Product* createProduct() = 0;
};
class ConcreteFactoryA : public Factory {
public:
Product* createProduct() override {
return new ConcreteProductA();
}
};
class ConcreteFactoryB : public Factory {
public:
Product* createProduct() override {
return new ConcreteProductB();
}
};
#include<vector>
#include<algorithm>
class Observer {
public:
virtual void update() = 0;
};
class Subject {
public:
void addObserver(Observer* observer) {
observers.push_back(observer);
}
void removeObserver(Observer* observer) {
observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
}
void notifyObservers() {
for (auto observer : observers) {
observer->update();
}
}
private:
std::vector<Observer*> observers;
};
class Target {
public:
virtual void request() = 0;
};
class Adaptee {
public:
void specificRequest() {
// ...
}
};
class Adapter : public Target {
public:
void request() override {
adaptee.specificRequest();
}
private:
Adaptee adaptee;
};
這些設計模式只是《C++ Cookbook》中的一部分內容,書中還包含了許多其他實用的C++編程技巧和最佳實踐。如果你對這些設計模式感興趣,可以考慮閱讀這本書以獲取更多詳細信息和示例。