《C++ Cookbook》是一本關(guān)于C++編程的實(shí)用指南,其中包含了許多設(shè)計(jì)模式的實(shí)現(xiàn)方法
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;
};
這些設(shè)計(jì)模式只是《C++ Cookbook》中的一部分內(nèi)容,書中還包含了許多其他實(shí)用的C++編程技巧和最佳實(shí)踐。如果你對(duì)這些設(shè)計(jì)模式感興趣,可以考慮閱讀這本書以獲取更多詳細(xì)信息和示例。