设计模式分类

发布时间:2023-05-23

一、创建型模式

创建型模式是指将对象的创建与使用分离,让系统更加灵活地创建对象。常见的创建型模式包括:

1. 工厂模式

工厂模式是一种高级抽象的创建型模式,它利用工厂类(Factory)负责创建其他对象。工厂模式可以分为简单工厂模式、工厂方法模式和抽象工厂模式。以下是一个简单工厂模式的代码示例:

class Animal{
public:
    virtual void speak() = 0;
};
class Dog : public Animal{
public:
    void speak() override{
        std::cout << "汪汪汪" << std::endl;
    }
};
class Cat : public Animal{
public:
    void speak() override{
        std::cout << "喵喵喵" << std::endl;
    }
};
class AnimalFactory{
public:
    Animal* createAnimal(const std::string& type){
        if(type == "Dog"){
            return new Dog();
        }
        else if(type == "Cat"){
            return new Cat();
        }
        else{
            return nullptr;
        }
    }
};
int main(){
    AnimalFactory factory;
    Animal* a1 = factory.createAnimal("Dog");
    Animal* a2 = factory.createAnimal("Cat");
    if(a1 != nullptr){
        a1->speak();
    }
    if(a2 != nullptr){
        a2->speak();
    }
    delete a1;
    delete a2;
    return 0;
}

2. 单例模式

单例模式是一种只允许一个对象实例的创建型模式,它常用于系统中全局状态的管理。以下是一个单例模式的代码示例:

class Singleton{
private:
    Singleton(){}
    static Singleton* instance;
public:
    static Singleton* getInstance(){
        if(instance == nullptr){
            instance = new Singleton();
        }
        return instance;
    }
};
Singleton* Singleton::instance = nullptr;
int main(){
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();
    std::cout << (s1 == s2) << std::endl; //输出1
    return 0;
}

二、结构型模式

结构型模式是指如何将类和对象按照某种布局组成更大的结构。常见的结构型模式包括:

1. 适配器模式

适配器模式是一种将两个不兼容的接口互相转换的结构型模式,它常用于将老系统中的接口转换为新系统中的接口。以下是一个类适配器模式的代码示例:

class Target{
public:
    virtual void request() = 0;
};
class Adaptee{
public:
    void specificRequest(){
        std::cout << "适配器模式示例" << std::endl;
    }
};
class Adapter : public Target{
private:
    Adaptee* adaptee;
public:
    Adapter(Adaptee* a){
        adaptee = a;
    }
    void request() override{
        adaptee->specificRequest();
    }
};
int main(){
    Adaptee* a = new Adaptee();
    Target* t = new Adapter(a);
    t->request();
    delete a;
    delete t;
    return 0;
}

2. 装饰器模式

装饰器模式是一种动态地给对象添加功能的结构型模式,它常用于不想增加子类的情况下,对对象的功能进行扩展。以下是一个装饰器模式的代码示例:

class Component{
public:
    virtual void operation() = 0;
};
class ConcreteComponent : public Component{
public:
    void operation() override{
        std::cout << "装饰器模式示例" << std::endl;
    }
};
class Decorator : public Component{
protected:
    Component* component;
public:
    Decorator(Component* c){
        component = c;
    }
    void operation() override{
        if(component != nullptr){
            component->operation();
        }
    }
};
class ConcreteDecorator : public Decorator{
public:
    ConcreteDecorator(Component* c) : Decorator(c){}
    void operation() override{
        Decorator::operation();
        std::cout << "被装饰" << std::endl;
    }
};
int main(){
    Component* c1 = new ConcreteComponent();
    c1->operation();
    Component* c2 = new ConcreteDecorator(c1);
    c2->operation();
    delete c1;
    delete c2;
    return 0;
}

三、行为型模式

行为型模式是指对象之间的通信方式及其分配职责的方式,常见的行为型模式包括:

1. 观察者模式

观察者模式是一种对象间的一对多依赖关系,当一个对象的状态发生改变时,它的所有依赖者都会收到通知。以下是一个观察者模式的代码示例:

class Subject;
class Observer{
public:
    virtual void update(Subject* s) = 0;
};
class Subject{
private:
    std::vector<Observer*> observers;
public:
    void attach(Observer* o){
        observers.push_back(o);
    }
    void detach(Observer* o){
        auto iter = std::find(observers.begin(), observers.end(), o);
        if(iter != observers.end()){
            observers.erase(iter);
        }
    }
    void notify(){
        for(auto obs: observers){
            obs->update(this);
        }
    }
    virtual int getState() = 0;
    virtual void setState(int state) = 0;
};
class ConcreteSubject : public Subject{
private:
    int state;
public:
    int getState() override{
        return state;
    }
    void setState(int s) override{
        state = s;
        notify();
    }
};
class ConcreteObserver : public Observer{
public:
    void update(Subject* s) override{
        std::cout << "观察者收到通知,当前状态为" << s->getState() << std::endl;
    }
};
int main(){
    Subject* s = new ConcreteSubject();
    Observer* o1 = new ConcreteObserver();
    Observer* o2 = new ConcreteObserver();
    s->attach(o1);
    s->attach(o2);
    s->setState(1);
    s->detach(o1);
    s->setState(2);
    delete s;
    delete o1;
    delete o2;
    return 0;
}

2. 策略模式

策略模式是一种将不同算法封装起来,使它们可以相互替换的行为型模式,它常用于将算法的变化独立于使用算法的客户端。以下是一个策略模式的代码示例:

class Strategy{
public:
    virtual int doOperation(int a, int b) = 0;
};
class AddStrategy : public Strategy{
public:
    int doOperation(int a, int b) override{
        return a + b;
    }
};
class SubStrategy : public Strategy{
public:
    int doOperation(int a, int b) override{
        return a - b;
    }
};
class Context{
private:
    Strategy* strategy;
public:
    void setStrategy(Strategy* s){
        strategy = s;
    }
    int executeStrategy(int a, int b){
        return strategy->doOperation(a, b);
    }
};
int main(){
    Context* c = new Context();
    c->setStrategy(new AddStrategy());
    std::cout << c->executeStrategy(1, 2) << std::endl;
    c->setStrategy(new SubStrategy());
    std::cout << c->executeStrategy(3, 2) << std::endl;
    delete c;
    return 0;
}