《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++编程技巧和最佳实践。如果你对这些设计模式感兴趣,可以考虑阅读这本书以获取更多详细信息和示例。