小工具知识网

当前位置: 首页 > 行业知识 > 设计模式精解:GoF 23种设计模式全解析

行业知识

设计模式精解:GoF 23种设计模式全解析

2026-11-06 10:09:09 来源:互联网转载

在软件工���中,设计模式是为了解决常见的软件设计问题而形成的一套经典解决方案。这些模式不仅能够帮助开发者提高设计的灵活性和代码的重用性,还能使问题的解决方案更加清晰、易于理解。《设计模式精解-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 parts_;    void ListParts()const {        std::cout 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 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 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 flyweights_.clear();    }    Flyweight* GetFlyweight(const std::vector& shared_state) {        std::string key = this->GetKey(shared_state);        if (this->flyweights_.find(key) == this->flyweights_.end()) {            std::cout flyweights_.insert(std::make_pair(key, new Flyweight(key)));        } else {            std::cout flyweights_.at(key);    }    void ListFlyweights() const {        size_t count = this->flyweights_.size();        std::cout 

上一篇:简单的ps海报怎么做?

下一篇:服务器底层怎么进系统的?