设计模式总结

一、创建型模式

1.单例模式

只能够创建一个类对象

#include 
#include 
#include 
using namespace std;

class Singleton{
    public:
        static Singleton* instance() {
            if (_instance == nullptr) {
                _mtx.lock();
                 this_thread::sleep_for(chrono::milliseconds(10));
                 if (_instance == nullptr) _instance = new Singleton();
                _mtx.unlock();
            }
            return _instance;
        }
    private:
        Singleton() {}
        ~Singleton() {}
        static Singleton* _instance;
        static mutex _mtx;
};

Singleton* Singleton::_instance = nullptr;
mutex Singleton::_mtx;

void getInstance() {
    cout << Singleton::instance() << endl;
}

int main() {
    thread t1(&getInstance);
    thread t2(&getInstance);
    thread t3(&getInstance);
    t1.join();
    t2.join();
    t3.join();
    return 0;
}

2.工厂模式

通过一个工厂建造不同产品

#include 
using namespace std;

class AbstractCar{
public:
    virtual void printName() = 0;
};

class BMW : public AbstractCar {
public:
    void printName() override {
        cout << "name = BMW\n";
    }
};

class BENZ : public AbstractCar {
public:
    void printName() override {
        cout << "name = BENZ\n";
    }
};

class Factory {
public:
    AbstractCar* getCar(std::string name) {
        if (name == "BMW") {
            return new BMW();
        } else if (name == "BENZ") {
            return new BENZ();
        } else {
            return nullptr;
        }      
    }
};

int main() {
    Factory factory;
    AbstractCar* arr[5];
    arr[0] = factory.getCar("BMW");
    arr[1] = factory.getCar("BENZ");
    arr[2] = factory.getCar("AUDI");
    arr[3] = factory.getCar("TOYOTA");
    arr[4] = factory.getCar("BENZ");
    for (auto it : arr) {
        if (it)
            it->printName();
        else
            cout << "object is nullptr" << endl;
    }
    return 0;
}

设计模式总结_第1张图片

3.建造者模式

通过不同建造器来创建不同产品

#include 
#include 
using namespace std;

class AbstractCar {
protected:
    int wheel;
    int engine;
    int color;
public:
    virtual void printName() = 0;
    virtual void debug() = 0;
};

class  BMW : public AbstractCar {
public:
    void printName() override {
        cout << "name = BMW\n";
    }
    void debug() override {
        cout << "name = BMW wheel = " << wheel << " engine = " << engine  << " color = " << color << endl;
    }
};

class  BENZ : public AbstractCar {
public:
    void printName() override {
        cout << "name = BENZ\n";
    }
    void debug() override {
        cout << "name = BENZ wheel = " << wheel << " engine = " << engine  << " color = " << color << endl;
    }
};

class AbstractBuilder{
public:
    virtual void buildA(AbstractCar* car) = 0;
    virtual void buildB(AbstractCar* car) = 0;
    virtual void buildC(AbstractCar* car) = 0;
    virtual AbstractCar* getCar() = 0;
};

class BMWBuilder : public AbstractBuilder {
public:
    void buildA(AbstractCar* car) override {
        cout << car << " BMW buildA \n";
    }
    void buildB(AbstractCar* car) override {
        cout << car << " BMW buildB \n";
    }
    void buildC(AbstractCar* car) override {
        cout << car << " BMW buildC \n";
    }
    AbstractCar* getCar() override {
        AbstractCar* car = new BMW();
        buildA(car);
        buildB(car);
        buildC(car);
        return car;
    }
};

class BENZBuilder : public AbstractBuilder {
public:
    void buildA(AbstractCar* car) override {
        cout << car << " BENZ buildA \n";
    }
    void buildB(AbstractCar* car) override {
        cout << car << " BENZ buildB \n";
    }
    void buildC(AbstractCar* car) override {
        cout << car << " BENZ buildC \n";
    }
    AbstractCar* getCar() override {
        AbstractCar* car = new BENZ();
        buildC(car);
        buildA(car);
        buildB(car);
        return car;
    }
};

class Factory {
private:
    AbstractBuilder* _builder;
public:
    void setBuilder(AbstractBuilder* builder) {
        _builder = builder;
    }
    AbstractCar* buildCar() {
        if (_builder)
            return _builder->getCar();
        return nullptr;
    }
};

int main() {
    Factory factory;
    BMWBuilder* builder1 = new BMWBuilder();
    BENZBuilder* builder2 = new BENZBuilder();
    factory.setBuilder(builder1);
    auto car1 = factory.buildCar();
    car1->debug();
    delete car1;

    factory.setBuilder(builder2);
    auto car2 = factory.buildCar();
    car2->debug();
    delete car2;

    delete builder1;
    delete builder2;
    return 0;
}

设计模式总结_第2张图片

 

4.原型模式

通过自身来复制一个对象

#include 
#include 
using namespace std;

class AbstractProto {
public:
    virtual AbstractProto* clone() = 0;
    virtual void print() = 0;
};

class ProtoTypeA: public AbstractProto {
public:
    AbstractProto* clone() override {
        return new ProtoTypeA(*this);
    }
    void print() override {
        cout << "ProtoTypeA --- print\n";
    }
};

class ProtoTypeAA: public ProtoTypeA {
public:
    AbstractProto* clone() override {
        return new ProtoTypeAA(*this);
    }
    void print() override {
        cout << "ProtoTypeAA --- print\n";
    }
};

// AbstractProto* clone(AbstractProto* obj) {
//     auto p1 = dynamic_cast(obj);
//     auto p2 = dynamic_cast(obj);
//     if (p1) {
//         return new ProtoTypeA(obj);     //不可行
//     }
// }

int main() {
    AbstractProto* p1 = new ProtoTypeA();
    AbstractProto* p2 = new ProtoTypeAA();
    auto p3 = p1->clone();
    auto p4 = p2->clone();

    p3->print();
    p4->print();

    delete p4;
    delete p3;
    delete p2;
    delete p1;
    return 0;
}

二、 结构型模式

1.桥接模式

使用委托方式将抽象和实现彻底地解耦,好处是抽象和实现可分别独立变化,系统耦合性得到很好降低。

#include 
#include 
using namespace std;

class ISoft {
public:
    virtual void run() = 0;
};

class IPhone {
public:
    IPhone() : _soft(nullptr) {}
    virtual void runSoft() = 0;
    void installSoft(ISoft* soft) {
        _soft = soft;
    }
protected:
    ISoft* _soft;
};

class PhoneA : public IPhone {
public:
    void runSoft() override {
        if (_soft) {
            cout << "PhoneA start launch soft\n";
            _soft->run();
        } else {
            cout << "PhoneA start launch soft is null\n";
        }
    }
};

class PhoneB : public IPhone {
public:
    void runSoft() override {
        if (_soft) {
            cout << "PhoneB start launch soft\n";
            _soft->run();
        } else {
            cout << "PhoneB start launch soft is null\n";
        }
    }
};

class SoftA : public ISoft {
public:
    void run() override {
        cout << "Soft A IS RUNNING \n";
    }
};

class SoftB : public ISoft {
public:
    void run() override {
        cout << "Soft B IS RUNNING \n";
    }
};

int main() {
    ISoft* pSoft1 = new SoftA();
    ISoft* pSoft2 = new SoftB();
    IPhone* p1 = new PhoneA();
    IPhone* p2 = new PhoneB();

    p1->installSoft(pSoft2);
    p2->installSoft(pSoft1);
    p1->runSoft();
    p2->runSoft();

    delete p2;
    delete p1;
    delete pSoft2;
    delete pSoft1;
    return 0;
}

 2.适配器模式

将一个类的接口转换成客户希望的另一个接口。该模式使原本由于接口不兼容而不能一起工作的那些类可一起工作。

#include 
#include 
using namespace std;

class Target {
public:
    virtual int request() = 0;
};

class Adaptee {
public:
    virtual int specialRequest() {
        cout << "Adaptee Special Request\n";
        return 66;
    }
};

class Adapter : public Target, public Adaptee {
public:
    int request() override {
        return this->specialRequest();
    }
};

class AAdapter : public Target {
private:
    Adaptee* _adaptee;
public:
    AAdapter() = delete;
    AAdapter(Adaptee* p) : _adaptee(p) {}
    int request() override {
        return _adaptee->specialRequest();
    }
};

//外部接口需求
void interfaceRequest(Target* target) {
    auto ret = target->request();
    cout << "ret = " << ret << endl;
}

int main() {
    Adapter* adapter = new Adapter();
    interfaceRequest(adapter);
    delete adapter;

    Adaptee* adaptee = new Adaptee();
    AAdapter* aadapter = new AAdapter(adaptee);
    interfaceRequest(aadapter);
    delete aadapter;
    delete adaptee;

    return 0;
}

3.装饰器者模式

装饰者提供一种给类增加职责的方法,非通过继承实现,通过组合。

#include 
#include 
using namespace std;

class AbstractPerson {
public:
    virtual void run() = 0;
    virtual void walk() = 0;
};

class Person : public AbstractPerson {
public:
    void run() override {
        cout << "Person run \n";
    }
    void walk() override {
        cout << "Person walk \n";
    }
};

class AbstractDecorator : public AbstractPerson {
protected:
    AbstractPerson* _person;
public:
    AbstractDecorator(AbstractPerson* p) : _person(p) {}
    virtual ~AbstractDecorator() {}

    void run() override {
        cout << "AbstractDecorator Person run \n";
        _person->run();
    }
    void walk() override {
        cout << "AbstractDecorator Person walk \n";
        _person->walk();
    }
};

class PersonBlack : public AbstractDecorator {
public:
    using AbstractDecorator::AbstractDecorator;
    void run() override {
        cout << "Black Person run fast\n";
        _person->run();
        _person->run();
    }
    void walk() override {
        cout << "Black Person walk fast\n";
        _person->walk();
        _person->walk();
    }
};

class PersonOld : public AbstractDecorator {
public:
    using AbstractDecorator::AbstractDecorator;
    void run() override {
        cout << "Old Person cannot run\n";
    }
    void walk() override {
        cout << "Old Person walk slowly\n";
        _person->walk();
    }
};

//外部可调用接口,无法做修改
void executeRun(AbstractPerson* p) {
    p->run();
}

void executeWalk(AbstractPerson* p) {
    p->walk();
}

int main() {
    AbstractPerson* p = new Person();
    executeRun(p);
    executeWalk(p);

    PersonBlack* p1 = new PersonBlack(p);
    PersonOld* p2 = new PersonOld(p);
    cout << "---------------decorator black---------------\n";
    executeRun(p1);
    executeWalk(p1);
    cout << "---------------decorator old---------------\n";
    executeRun(p2);
    executeWalk(p2);

    delete p2;
    delete p1;
    delete p;
    return 0;
}

设计模式总结_第3张图片

 

4.外观模式

为子系统中一组接口提供一个一致接口,使子系统更加容易使用。

#include 
#include 
using namespace std;

class ISystem {
public:
    virtual bool Register() = 0;
    virtual bool Login() = 0;
};

class SystemA: public ISystem {
public:
    bool Register() override {
        cout << "SystemA register\n";
        return true;
    }
    bool Login() override {
        cout << "SystemA login\n";
        return true;
    }
};

class SystemB: public ISystem {
public:
    bool Register() override {
        cout << "SystemB register\n";
        return true;
    }
    bool Login() override {
        cout << "SystemB login\n";
        return true;
    }
};

class SystemC: public ISystem {
public:
    bool Register() override {
        cout << "SystemC register\n";
        return true;
    }
    bool Login() override {
        cout << "SystemC login\n";
        return true;
    }
};

class Facade : public ISystem {
protected:
    vector _systems;

public:
    bool Register() override {
        for (auto p: _systems) {
            p->Register();
        }
        return true;
    }
    bool Login() override {
        for (auto p: _systems) {
            p->Login();
        }
        return true;
    }
    void addSystem(ISystem* system) {
        _systems.push_back(system);
    }
};

int main() {
    Facade facade;
    ISystem* sys1 = new SystemA();
    ISystem* sys2 = new SystemB();
    ISystem* sys3 = new SystemC();
    facade.addSystem(sys1);
    facade.addSystem(sys2);
    facade.addSystem(sys3);

    facade.Register();
    facade.Login();

    delete sys1;
    delete sys2;
    delete sys3;
    return 0;
}

设计模式总结_第4张图片

 

5.代理模式/委托模式

作用是找一个代理对象来替我们访问某个对象。

#include 
#include 
using namespace std;

class Person{
public:
    Person() : _proxy(nullptr) {}
    virtual ~Person() {}

    virtual void rentHouse() = 0;
    virtual void setProxy(Person* p) {_proxy = p;}

protected:
    Person* _proxy;
};

class Proxy : public Person {
public:
    using Person::Person;
    void rentHouse() override {
        if (!_proxy) return;
        cout << "Proxy help to rent house\n";
        _proxy->rentHouse();
        cout << "Proxy need to charge fee as intermediary\n";
    }
};

class Master: public Person {
public:
    void rentHouse() override {
        cout << "Master need rent house\n";
    }
};

int main() {
    Person* p = new Master();
    Person* proxy = new Proxy();
    proxy->setProxy(p);
    proxy->rentHouse();

    delete p;
    delete proxy;
    return 0;
}

 6.享元模式

主要用于减少创建对象的数量,以减少内存占用和提供性能。这种类型的设计模式数据结构型模式,提供减少对象竖向从而改善应用所需的对象结构方式。

7.组合模式

用于把一组相似对象当做一个单一对象。依据树形结构来组合对象,用来表示部分以及整体层次。属于结构型模式,创建了对象组的树形结构。

三、行为型模式

1.模板方法模式

将逻辑算法放在抽象基类中,并定义好需要实现细节的接口,子类中实现细节。

#include 
#include 
using namespace std;

class Factory{
public:
    virtual void templateMethod() {
        this->buildA();
        this->buildB();
        this->buildC();
        this->buildD();
    }

    virtual void buildA() = 0;
    virtual void buildB() = 0;
    virtual void buildC() = 0;
    virtual void buildD() = 0;
};

class FactoryBMW: public Factory {
public:
    void buildA() override {
        cout << "BuildA in BMW Factory\n";
    }
    void buildB() override {
        cout << "buildB in BMW Factory\n";
    }
    void buildC() override {
        cout << "buildC in BMW Factory\n";
    }
    void buildD() override {
        cout << "buildD in BMW Factory\n";
    }
};

class FactoryBENZ: public Factory {
public:
    void buildA() override {
        cout << "BuildA in BENZ Factory\n";
    }
    void buildB() override {
        cout << "buildB in BENZ Factory\n";
    }
    void buildC() override {
        cout << "buildC in BENZ Factory\n";
    }
    void buildD() override {
        cout << "buildD in BENZ Factory\n";
    }
};

int main() {
    Factory* p1 = new FactoryBMW();
    Factory* p2 = new FactoryBENZ();
    p1->templateMethod();
    p2->templateMethod();

    delete p1;
    delete p2;
    return 0;
}

设计模式总结_第5张图片

2.策略模式

策略模式同模板模式,都是未了给业务逻辑具体实现和抽象接口之间的解耦。策略模式将逻辑算法封装到一个类里面,通过组合方式将具体算法实现在组合对象中实现,再通过委托方式将抽象接口的实现委托组合对象实现。

#include 
using namespace std;

class Strategy{
public:
    virtual void sort(int arr[], int n) = 0;
};

class Context {
public:
    void setData(int* data, int size) {
        _arr = data;
        _size = size;
    }
    void setStrategy(Strategy* p) {
        _strategy = p;
    }
    void sort() {
        if (_strategy && _arr)
            _strategy->sort(_arr, _size);
    }
    void print() {
        for (int i = 0; i < _size; ++i) {
            cout << _arr[i] << " ";
        }
        cout << endl;
    }

private:
    int* _arr;
    int _size;
    Strategy* _strategy;
};

class BubbleSort : public Strategy {
public:
    void sort(int arr[], int size) override {
        cout << "Bubble sort\n";
        if (size <= 1) return;
        for (int i = 1; i < size; i++) {
            for (int j = i -1; j >= 0; j--) {
                if (arr[j] > arr[j+1]) {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
                else {
                    break;
                }
            }
        }
    }
};

class InsertSort : public Strategy {
public:
    void sort(int a[], int n) override {
        cout << "Insert Sort\n";
        if (n <= 1) return;
        for (int i = 0; i < n - 1; i++) {
            int minID = i;
            for (int j = i + 1; j < n; j++) {
                if (a[j] < a[minID]) {
                    minID = j;
                }
            }
            int temp = a[i];
            a[i] = a[minID];
            a[minID] = temp;
        }
    }
};

class SelectSort : public Strategy {
public:
    void sort(int a[], int n) override {
        cout << "Select Sort \n";
        if (n <= 1) return;
        for (int i = 0; i < n - 1; i++) {
            int minID = i;
            for (int j = i + 1; j < n; j++) {
                if (a[j] < a[minID]) {
                    minID = j;
                }
            }
            int temp = a[i];
            a[i] = a[minID];
            a[minID] = temp;
        }
    }
};

int main() {
    Context* ctx = new Context();
    int arr[] = {23, 34, 1,24 ,34,434,343,2, 2,4 ,5 ,5,242, 3, 5, 2,87,89};
    ctx->setData(arr, sizeof(arr)/sizeof(int));
    Strategy* p1 = new BubbleSort();
    Strategy* p2 = new InsertSort();
    Strategy* p3 = new SelectSort();

    ctx->setStrategy(p2);
    ctx->sort();
    ctx->print();

    delete p1;
    delete p2;
    delete p3;
    delete ctx;
    return 0;
}

 3.观察者模式

解决问题为:建立一个subject对多个observer的依赖关系,并且做到当一变化时,依赖这个一的多也能够同步变化。

#include 
#include 
#include 
#include 
using namespace std;

class Subject;
class AbstractObserver{
public:
    AbstractObserver(string name) : _name(name) {}
    virtual void update(Subject* p) = 0;
    inline string getName() {return _name;}
protected:
    string _name;
};

class ObserverA :  public AbstractObserver{
public:
    using AbstractObserver::AbstractObserver;
    void update(Subject* p) override {
        cout << "Update ObserverA name = " << _name << " this =  " << this << endl;
    }
};

class ObserverB :  public AbstractObserver{
public:
    using AbstractObserver::AbstractObserver;
    void update(Subject* p) override {
        cout << "Update ObserverB name = " << _name << " this =  " << this << endl;
    }
};

class Subject{
public:
    void addObserver(AbstractObserver* p) {
        auto arr = _observers.find(p->getName());
        if (arr == _observers.end()) {
            vector vec;
            vec.push_back(p);
            _observers[p->getName()] = vec;
        } else {
            _observers[p->getName()].push_back(p);
        }
        //_observers[p->getName()] = p;
    }
    void notify(string s) {
        if (_observers.find(s) != _observers.end()) {
            for (auto p: _observers[s])
                p->update(this);
        } else {
            cout << "not found and observers\n" << endl;
            // for (auto p : _observers) {
            //     p.second->update(this);
            // }
        }
    }
protected:
    map> _observers;
};

int main() {
    Subject Subject;
    AbstractObserver* p1 = new ObserverA("abc");
    AbstractObserver* p2 = new ObserverA("abdfsdss");
    AbstractObserver* p3 = new ObserverA("23rf");
    AbstractObserver* p4 = new ObserverA("abc");    
    AbstractObserver* p5 = new ObserverA("fsf");
    AbstractObserver* p6 = new ObserverA("vxcv3");

    Subject.addObserver(p1);
    Subject.addObserver(p2);
    Subject.addObserver(p3);
    Subject.addObserver(p4);
    Subject.addObserver(p5);
    Subject.addObserver(p6);

    Subject.notify("abc");

    delete p1;
    delete p2;
    delete p3;
    delete p4;
    delete p5;
    delete p6;
    return 0;
}

 4.命令模式

通过将请求封装到一个对象中,并将请求的接受者存档到具体的ConcreteCommand类中Receiver中,从而实现调用操作的对象和操作的具体实现者之间的解耦。

#include 
using namespace std;

class Receiver {
public:
    virtual void action() {
        cout << "Execute command\n";
    }
};

class ReceiverA : public Receiver {
public:
    virtual void action() {
        cout << "Execute command A\n";
    }
};

class Command {
public:
    Command(Receiver* p) : _receiver(p) {}
    virtual void setReceiver(Receiver* p) {_receiver = p;}
    virtual void doCommand(int n) = 0;
protected:
    Receiver* _receiver;
};

class CommandA : public Command {
public:
    using Command::Command;
    CommandA(Receiver* p, Receiver* p2) : Command(p), _receiver2(p2) {

    }
    void setReceiver2(Receiver* p) {_receiver2 = p;}
    void doCommand(int n) override {
        if (n == 0)
            _receiver->action();
        else
            _receiver2->action();
    }
protected:
    Receiver* _receiver2;
};

class CommandB : public Command {
public:
    void doCommand(int n) override {
        cout << "CommandB doCommand\n";
        _receiver->action();
    }
};

class Invoker {
public:
    Invoker() : _command(nullptr) {}
    void setCommand(Command* p) {
        _command = p;
    }
    void executeCommand(int n = 0) {
        if (_command) _command->doCommand(n);
    }
protected:
    Command* _command;
};

int main() {
    Invoker* invoker = new Invoker();
    Receiver* recv = new Receiver();
    ReceiverA* recvA = new ReceiverA();
    Command* command = new CommandA(recv, recvA);

    invoker->setCommand(command);
    invoker->executeCommand();
    invoker->executeCommand(1);

    delete command;
    delete recvA;
    delete recv;
    delete invoker;
    return 0;
}

 5.访问者模式

不改变类的前提下定义作用于这些元素的新操作。

#include 
using namespace std;

class Node;
class Visitor {
public:
    virtual void visit(Node* node) = 0;
};

class Node{
public:
    virtual void accept(Visitor* visitor) = 0;
};

class NodeA : public Node {
    friend class VisitorA;
public:
    NodeA() {
        s = "hello tra";
    }
    void accept(Visitor* visitor) override {
        visitor->visit(this);
    }
protected:
    string s;
};

class NodeB : public Node {
    friend class VisitorB;
public:
    NodeB() {
        s = "hello taffee";
    }
    void accept(Visitor* visitor) override {
        visitor->visit(this);
    }
protected:
    string s;
};

class VisitorA : public Visitor {
public:
    void visit(Node* node) override {
        NodeA* p = dynamic_cast(node);
        if (p) {
            cout << "Node A ---" << p->s.c_str() << endl;
        }
    }
};

class VisitorB : public Visitor {
public:
    void visit(Node* node) override {
        NodeB* p = dynamic_cast(node);
        if (p) {
            cout << "Node B ---" << p->s.c_str() << endl;
        }
    }
};

int main() {
    Node* p1 = new NodeA();
    Node* p2 = new NodeB();
    VisitorA* p3 = new VisitorA();
    VisitorB* p4 = new VisitorB();
    p1->accept(p3);
    p2->accept(p4);

    delete p4;
    delete p3;
    delete p2;
    delete p1;

    return 0;
}

 6.责任链模式

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

#include 
using namespace std;

struct Request{
    int days;
    int type;
    string desc;
};

class Handler{
public:
    Handler() : _nextHandler(nullptr) {}
    virtual void setNextHandler(Handler* p) {_nextHandler = p;}
    virtual void dealRequest(Request* p) = 0;
    virtual void postRequest(int day, int type, string desc) {
        Request* p = new Request{day, type, desc};
        this->dealRequest(p);
        delete p;
    }
protected:
    Handler* _nextHandler;
};

class Employee : public Handler {
public:
    void dealRequest(Request* p) override {
        cout << "没有权限,需要上级审核\n";
        if (this->_nextHandler) {
            this->_nextHandler->dealRequest(p);
        }
    }
};

class TeamLeader : public Handler {
public:
    void dealRequest(Request* p) override {
        if (p->days <= 3)
            cout << "小于3天,直接通过审核\n";
        else if (this->_nextHandler) {
            cout << "没有权限,需要上级审核\n";
            this->_nextHandler->dealRequest(p);
        }
    }
};

class Manager : public Handler {
public:
    void dealRequest(Request* p) override {
        if (p->days <= 7)
            cout << "小于7天,直接通过审核\n";
        else if (this->_nextHandler) {
            cout << "没有权限,需要上级审核\n";
            this->_nextHandler->dealRequest(p);
        }
    }
};

class Boss : public Handler {
public:
    void dealRequest(Request* p) override {
        if (p->days <= 15)
            cout << "小于15天,直接通过审核\n";
        else if (this->_nextHandler) {
            cout << "没有权限,需要上级审核\n";
            this->_nextHandler->dealRequest(p);
        }
        else {
            cout << "大于15天,拒绝\n";
        }
    }
};

int main() {
    Handler* p1 = new Boss();
    Handler* p2 = new Manager();
    Handler* p3 = new TeamLeader();
    Handler* p4 = new Employee();
    p1->setNextHandler(nullptr);
    p2->setNextHandler(p1);
    p3->setNextHandler(p2);
    p4->setNextHandler(p3);

    //p4->postRequest(2, 0, "事假");
    //p4->postRequest(6, 1, "病假");
    p4->postRequest(15, 2, "婚假");
    delete p1;
    delete p2;
    delete p3;
    delete p4;
    return 0;
}

 7.迭代器模式

提供一种顺序访问一个聚合对象中各个元素,而不暴露该对象的内部表示。

8.备忘录模式

保存一个对象的某个状态,以便在适当的时候恢复对象。属于行为型模式。

#include 
#include 
using namespace std;

struct StateInfo
{
    int a, b;
};


class CareTaker{
public:
    static CareTaker* _instance;
    static CareTaker* instance() {
        if (_instance == nullptr) {
            _instance = new CareTaker();
        }
        return _instance;
    }
    virtual ~CareTaker() {
        for (auto it : _states) {
            delete it;
        }
    }
    void addState(int a, int b) {
        _states.push_back(new StateInfo{a, b});
    }
    StateInfo* getState(int index) {
        if (_states.size() > index) {
            return _states[index];
        }
        return nullptr;
    }
protected:
    vector _states;
};

class Originator{
public:
    Originator() : _a(0), _b(0) {}
    void SetA(int a) {
        _a = a;
        this->saveState();
    }
    void SetB(int b) {
        _b = b;
        this->saveState();
    }
    void saveState() {
        CareTaker::instance()->addState(_a, _b);
    }
    void recoverState(int index) {
        auto p = CareTaker::instance()->getState(index);
        if (p) {
            _a = p->a;
            _b = p->b;
        }
        cout << "a = " << _a << " b = " << _b << endl;
    }

private:
    int _a, _b;
};

CareTaker* CareTaker::_instance = nullptr;
int main() {
    Originator* p = new Originator();
    p->SetA(1);
    p->SetA(2);
    p->SetB(4);
    p->SetA(324);
    p->SetB(23);
    p->SetA(3);

    //index 从0开始的
    cout << "-------------恢复第1步-------------" << endl;
    p->recoverState(1);

    cout << "-------------恢复第5步-------------" << endl;
    p->recoverState(5);

    cout << "-------------恢复第15步-------------" << endl;
    p->recoverState(15);
    return 0;
}

设计模式总结_第6张图片

 9.中介者模式

用来降低多个对象和类之间的通信复杂性。提供一个中介类,该类通常处理不同类之间的通信,并直接松耦合,使代码易于维护。

#include 
#include 
using namespace std;

class Colleague;
class Mediator{
public:
    virtual void deal(Colleague* p) = 0;
    virtual void setColleague(Colleague* from, Colleague* to) {
        _from = from;
        _to = to;
    }

protected:
    Colleague* _from;
    Colleague* _to;
};

class Colleague {
public:
    Colleague(Mediator* p) : _mediator(p) {}
    virtual void send() = 0;
    virtual void receive(string s) = 0;
protected:
    Mediator* _mediator;
};

class ColleagueA : public Colleague {
public:
    using Colleague::Colleague;
    void send() override {
        _mediator->deal(this);
    }
    void receive(string s) override {
        cout << "A----"<< s.c_str() << endl;
    }
};

class ColleagueB : public Colleague {
public:
    using Colleague::Colleague;
    void send() override {
        _mediator->deal(this);
    }
    void receive(string s) override {
        cout << "B----"<< s.c_str() << endl;
    }
};

class MediatorA : public Mediator {
public:
    void deal(Colleague* p) override {
        if (p == _from) {
            _from->receive("from--->to");
        } else {
            _to->receive("to--->from");
        }
    }
};

int main() {
    Mediator* mediator = new MediatorA();
    Colleague* p1 = new ColleagueA(mediator);
    Colleague* p2 = new ColleagueB(mediator);
    mediator->setColleague(p1, p2);
    p1->send();
    p2->send();
    delete p1;
    delete p2;
    delete mediator;
    return 0;
}

 10.解释者模式

提供评估语言的语法或表达式的方式。实现了一个表达式接口,该接口解释一个特定的上下文。被用在SQL解析、符号处理引擎等。

四、模式设计原则

1.设计原则

①面向对象设计模式:应对变化,提高复用的设计。

②设计模式要点:寻找变化点,然后再变化点处应用设计模式,从而来更好应对需求变化。

③设计模式应用不宜先入为主,没有一步到位的设计模式。

你可能感兴趣的:(设计模式,c++,开发语言,ubuntu)