在软件工程中,设计模式是为了解决常见的软件设计问题而形成的一套经典解决方案。这些模式不仅能够帮助开发者提高设计的灵活性和代码的重用性,还能使问题的解决方案更加清晰、易于理解。《设计模式精解-GoF 23种设计模式》一书中所列举的23种设计模式,是由四位作者(即GoF,Gang of Four)提出的,至今仍被广泛应用在各种软件开发项目中。本文将对这些设计模式进行全面解析,每种模式均配以C++代码示例,旨在为读者提供一个清晰、系统的学习路径。
创建型模式(Creational Patterns)
创建型模式涉及对象的创建机制,旨在创建对象时增加系统的灵活性和效率。
工厂模式(Factory Pattern)
工厂模式通过定义一个用于创建对象的接口,让子类决定实例化哪一个类。这样的方式允许在不明确指定具体类的情况下创建对象。
class Product {
public:
virtual ~Product() {}
virtual std::string Operation() const = 0;
};
class ConcreteProduct1 : public Product {
public:
std::string Operation() const override {
return "Result of ConcreteProduct1";
}
};
class Creator {
public:
virtual ~Creator(){}
virtual Product* FactoryMethod() const = 0;
std::string SomeOperation() const {
Product* product = this->FactoryMethod();
std::string result = "Creator: The same creator's code has just worked with " + product->Operation();
delete product;
return result;
}
};
抽象工厂模式(Abstract Factory Pattern)
抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
class AbstractProductA {
public:
virtual ~AbstractProductA(){};
virtual std::string UsefulFunctionA() const = 0;
};
class AbstractProductB {
public:
virtual ~AbstractProductB(){};
virtual std::string UsefulFunctionB() const = 0;
virtual std::string AnotherUsefulFunctionB(const AbstractProductA& collaborator) const = 0;
};
class ConcreteProductA1 : public AbstractProductA {
public:
std::string UsefulFunctionA() const override {
return "The result of the product A1.";
}
};
class ConcreteProductB1 : public AbstractProductB {
public:
std::string UsefulFunctionB() const override {
return "The result of the product B1.";
}
std::string AnotherUsefulFunctionB(const AbstractProductA& collaborator) const override {
const std::string result = collaborator.UsefulFunctionA();
return "The result of the B1 collaborating with ( " + result + " )";
}
};
单例模式(Singleton Pattern)
单例模式确保一个类只有一个实例,并提供一个全局访问点。
class Singleton {
protected:
Singleton(const std::string value): value_(value) {}
static Singleton* singleton_;
std::string value_;
public:
Singleton(Singleton &other) = delete;
void operator=(const Singleton &) = delete;
static Singleton *GetInstance(const std::string& value);
std::string value() const{
return value_;
}
};
Singleton* Singleton::singleton_ = nullptr;;
Singleton *Singleton::GetInstance(const std::string& value) {
if(singleton_ == nullptr){
singleton_ = new Singleton(value);
}
return singleton_;
}
建造者模式(Builder Pattern)
建造者模式使用多个简单的对象一步一步构建成一个复杂的对象。
class Product1 {
public:
std::vector<std::string> parts_;
void ListParts()const {
std::cout << "Product parts: ";
for (size_t i = 0; i < parts_.size(); i++) {
if (parts_[i] == parts_.back()) {
std::cout << parts_[i];
} else {
std::cout << parts_[i] << ", ";
}
}
std::cout << "\n\n";
}
};
class Builder {
public:
virtual ~Builder() {}
virtual void ProducePartA() const = 0;
virtual void ProducePartB() const = 0;
virtual void ProducePartC() const = 0;
};
class ConcreteBuilder1 : public Builder {
private:
Product1* product;
public:
ConcreteBuilder1() {
this->Reset();
}
~ConcreteBuilder1() {
delete product;
}
void Reset() {
this->product = new Product1();
}
void ProducePartA()const override {
this->product->parts_.push_back("PartA1");
}
void ProducePartB()const override {
this->product->parts_.push_back("PartB1");
}
void ProducePartC()const override {
this->product->parts_.push_back("PartC1");
}
Product1* GetProduct() {
Product1* result = this->product;
this->Reset();
return result;
}
};
原型模式(Prototype Pattern)
原型模式使用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
class Prototype {
protected:
std::string prototype_name_;
float prototype_field_;
public:
Prototype() {}
Prototype(std::string prototype_name)
: prototype_name_(prototype_name) {
}
virtual ~Prototype() {}
virtual Prototype *clone() const = 0;
virtual void Method(float prototype_field) {
this->prototype_field_ = prototype_field;
std::cout << "Call Method from " << this->prototype_name_ << " with field : " << this->prototype_field_ << std::endl;
}
};
class ConcretePrototype1 : public Prototype {
private:
float concrete_prototype_field1_;
public:
ConcretePrototype1(std::string prototype_name, float concrete_prototype_field)
: Prototype(prototype_name), concrete_prototype_field1_(concrete_prototype_field) {
}
Prototype *clone() const override {
return new ConcretePrototype1(*this);
}
};
class ConcretePrototype2 : public Prototype {
private:
float concrete_prototype_field2_;
public:
ConcretePrototype2(std::string prototype_name, float concrete_prototype_field)
: Prototype(prototype_name), concrete_prototype_field2_(concrete_prototype_field) {
}
Prototype *clone() const override {
return new ConcretePrototype2(*this);
}
};
结构型模式(Structural Patterns)
结构型模式关注于对象组合,它们利用继承和接口的方式来组合接口或实现以提供新的功能。
桥接模式(Bridge Pattern)
桥接模式通过将抽象部分与实现部分分离,使它们可以独立变化。
class Implementation {
public:
virtual ~Implementation() {}
virtual std::string OperationImplementation() const = 0;
};
class ConcreteImplementationA : public Implementation {
public:
std::string OperationImplementation() const override {
return "ConcreteImplementationA: Here's the result on the platform A.\n";
}
};
class ConcreteImplementationB : public Implementation {
public:
std::string OperationImplementation() const override {
return "ConcreteImplementationB: Here's the result on the platform B.\n";
}
};
class Abstraction {
protected:
Implementation* implementation_;
public:
Abstraction(Implementation* implementation) : implementation_(implementation) {
}
virtual ~Abstraction() {
}
virtual std::string Operation() const {
return "Abstraction: Base operation with:\n" +
this->implementation_->OperationImplementation();
}
};
class ExtendedAbstraction : public Abstraction {
public:
ExtendedAbstraction(Implementation* implementation) : Abstraction(implementation) {
}
std::string Operation() const override {
return "ExtendedAbstraction: Extended operation with:\n" +
this->implementation_->OperationImplementation();
}
};
适配器模式(Adapter Pattern)
适配器模式允许不兼容的接口之间的通信,它通过将一个类的接口转换成客户期望的另一个接口来实现。
class Target {
public:
virtual ~Target() {}
virtual std::string Request() const {
return "Target: The default target's behavior.";
}
};
class Adaptee {
public:
std::string SpecificRequest() const {
return ".eetpadA eht fo roivaheb laicepS";
}
};
class Adapter : public Target {
private:
Adaptee* adaptee_;
public:
Adapter(Adaptee* adaptee) : adaptee_(adaptee) {
}
std::string Request() const override {
std::string to_reverse = this->adaptee_->SpecificRequest();
std::reverse(to_reverse.begin(), to_reverse.end());
return "Adapter: (TRANSLATED) " + to_reverse;
}
};
装饰器模式(Decorator Pattern)
装饰器模式允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,因为这种模式通过创建一个装饰类来包装原有的类。
class Component {
public:
virtual ~Component() {}
virtual std::string Operation() const = 0;
};
class ConcreteComponent : public Component {
public:
std::string Operation() const override {
return "ConcreteComponent";
}
};
class Decorator : public Component {
protected:
Component* component_;
public:
Decorator(Component* component) : component_(component) {
}
std::string Operation() const override {
return this->component_->Operation();
}
};
class ConcreteDecoratorA : public Decorator {
public:
ConcreteDecoratorA(Component* component) : Decorator(component) {
}
std::string Operation() const override {
return "ConcreteDecoratorA(" + Decorator::Operation() + ")";
}
};
class ConcreteDecoratorB : public Decorator {
public:
ConcreteDecoratorB(Component* component) : Decorator(component) {
}
std::string Operation() const override {
return "ConcreteDecoratorB(" + Decorator::Operation() + ")";
}
};
组合模式(Composite Pattern)
组合模式允许将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
class Component {
protected:
Component* parent_;
public:
virtual ~Component() {}
void SetParent(Component* parent) {
this->parent_ = parent;
}
Component* GetParent() const {
return this->parent_;
}
virtual void Add(Component* component) {}
virtual void Remove(Component* component) {}
virtual bool IsComposite() const {
return false;
}
virtual std::string Operation() const = 0;
};
class Leaf : public Component {
public:
std::string Operation() const override {
return "Leaf";
}
};
class Composite : public Component {
protected:
std::list<Component*> children_;
public:
void Add(Component* component) override {
this->children_.push_back(component);
component->SetParent(this);
}
void Remove(Component* component) override {
children_.remove(component);
component->SetParent(nullptr);
}
bool IsComposite() const override {
return true;
}
std::string Operation() const override {
std::string result;
for (const Component* c : children_) {
if (c == children_.back()) {
result += c->Operation();
} else {
result += c->Operation() + "+";
}
}
return "Branch(" + result + ")";
}
};
享元模式(Flyweight Pattern)
享元模式是对象池的一种实现,它用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,因为该模式提供了减少对象数量从而改善应用所需的对象结构的方式。
class Flyweight {
protected:
std::string shared_state_;
public:
Flyweight(const std::string& shared_state) : shared_state_(shared_state) {
}
virtual ~Flyweight() {}
virtual void Operation(const std::string& unique_state) const {
std::cout << "Flyweight: Displaying shared (" << this->shared_state_ << ") and unique (" << unique_state << ") state.\n";
}
};
class FlyweightFactory {
private:
std::unordered_map<std::string, Flyweight*> flyweights_;
std::string GetKey(const std::vector<std::string>& state) const {
std::string key;
for (const std::string& s : state) {
key += s;
}
return key;
}
public:
FlyweightFactory(const std::vector<std::string>& initial_flyweights) {
for (const std::string& state : initial_flyweights) {
this->flyweights_.insert(std::make_pair<std::string, Flyweight*>(this->GetKey({state}), new Flyweight(state)));
}
}
~FlyweightFactory() {
for (auto pair : this->flyweights_) {
delete pair.second;
}
this->flyweights_.clear();
}
Flyweight* GetFlyweight(const std::vector<std::string>& shared_state) {
std::string key = this->GetKey(shared_state);
if (this->flyweights_.find(key) == this->flyweights_.end()) {
std::cout << "FlyweightFactory: Can't find a flyweight, creating new one.\n";
this->flyweights_.insert(std::make_pair(key, new Flyweight(key)));
} else {
std::cout << "FlyweightFactory: Reusing existing flyweight.\n";
}
return this->flyweights_.at(key);
}
void ListFlyweights() const {
size_t count = this->flyweights_.size();
std::cout << "\nFlyweightFactory: I have " << count << " flyweights:\n";
for (auto pair : this->flyweights_) {
std::cout << pair.first << "\n";
}
}
};
外观模式(Facade Pattern)
外观模式提供了一个统一的接口,用来访问子系统中的一群接口。外观定义了一个高层接口,让子系统更容易使用。
class Subsystem1 {
public:
std::string Operation1() const {
return "Subsystem1: Ready!\n";
}
std::string OperationN() const {
return "Subsystem1: Go!\n";
}
};
class Subsystem2 {
public:
std::string Operation1() const {
return "Subsystem2: Get ready!\n";
}
std::string OperationZ() const {
return "Subsystem2: Fire!\n";
}
};
class Facade {
protected:
Subsystem1* subsystem1_;
Subsystem2* subsystem2_;
public:
Facade(
Subsystem1* subsystem1 = nullptr,
Subsystem2* subsystem2 = nullptr) {