设计模式实例代码-C++版本

设计模式-C++实例代码

#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
#define SAFE_DELETE(x) \
    if(x)            \
    {                \
        delete x;    \
        x=nullptr;   \
    }                

创建型-简单工厂模式

创建型-简单工厂模式

//创建型-简单工厂模式
#if 0&&1
class Shape
{
public:
    virtual int Area()=0;
    virtual int Perimeter()=0;
    virtual void Show() = 0;
};

class Rectangle :public Shape
{
public:
    Rectangle(int length,int width){
        cout << "create Rectangle" << endl;
    }
    int Area()
    {
        cout << "1" << endl;
        return 0;
    }
    int Perimeter()
    {
        cout << "2" << endl;
        return 0;
    }
    void Show()
    {
        cout << "Rectangle" << endl;
    }
};

class Triangle :public Shape
{
public:
    Triangle(int hight,int bottom){
        cout << "create Triangle" << endl;
    }
    int Area()
    {
        cout << "3" << endl;
        return 0;
    }
    int Perimeter()
    {
        cout << "4" << endl;
        return 0;
    }
    void Show()
    {
        cout << "Triangle" << endl;
    }
};

class Circle :public Shape
{
public:
    Circle(int dia){
        cout << "create Circle" << endl;
    }
    int Area()
    {
        cout << "5" << endl;
        return 0;
    }
    int Perimeter()
    {
        cout << "6" << endl;
        return 0;
    }
    void Show()
    {
        cout << "Circle" << endl;
    }
};

class ShapeFactory
{
public:
    Shape * MakeShape(const string & shape_type)
    {
        Shape * ret = nullptr;
        if (shape_type == "Rectangle")
        {
            ret = new Rectangle(1, 2);
        }
        else if (shape_type == "Triangle")
        {
            ret = new Triangle(3, 4);
        }
        else if (shape_type == "Circle")
        {
            ret = new Circle(5);
        }
        return ret;
    }
};

int test_simple_factory()
{
    ShapeFactory factory;
    auto pShape=factory.MakeShape("Rectangle");
    pShape->Show();

    pShape = factory.MakeShape("Triangle");
    pShape->Show();

    pShape = factory.MakeShape("Circle");
    pShape->Show();
    return 0;
}
#endif

创建型-工厂方法模式

创建型-工厂方法模式

//创建型-工厂方法模式
#if 0&&2
class Product
{
public:
    virtual void showProduct() = 0;
};

class ProductA :public Product
{
public:
    //ProductA(){};
    void showProduct()
    {
        cout << "i am ProductA" << endl;
    }
};

class ProductB :public Product
{
public:
   // ProductB(){};
    void showProduct()
    {
        cout << "i am ProductB" << endl;
    }
};

class Factory
{
public:
    virtual void creatProduct() = 0;
};

class FactoryA
{
public:
    Product * creatProduct()
    {
        return (new ProductA());
    }
};

class FactoryB
{
public:
    Product * creatProduct()
    {
        return (new ProductB());
    }
};


void test_factory_function()
{
    FactoryA fa;
    auto proa=fa.creatProduct();
    proa->showProduct();

    FactoryB fb;
    auto prob = fb.creatProduct();
    prob->showProduct();
}
#endif

创建型-抽象工厂模式

创建型-抽象工厂模式

//创建型-抽象工厂模式
#if 0&&3
class ProductA
{
public:
    virtual void showProduct() = 0;
};

class ProductB
{
public:
    virtual void showProduct() = 0;
};

class ProductA1 :public ProductA
{
public:
    void showProduct()
    {
        cout << "i am ProductA 1" << endl;
    }
};

class ProductB1 :public ProductB
{
public:
    void showProduct()
    {
        cout << "i am ProductB 1" << endl;
    }
};

class ProductA2 :public ProductA
{
public:
    void showProduct()
    {
        cout << "i am ProductA 2" << endl;
    }
};

class ProductB2 :public ProductB
{
public:
    void showProduct()
    {
        cout << "i am ProductB 2" << endl;
    }
};

class Factory
{
public:
    virtual ProductA * creatProductA() = 0;
    virtual ProductB * creatProductB() = 0;
};

class Factory1
{
public:
    ProductA * creatProductA()
    {
        return (new ProductA1());
    }
    ProductB * creatProductB()
    {
        return (new ProductB1());
    }
};

class Factory2
{
public:
    ProductA * creatProductA()
    {
        return (new ProductA2());
    }
    ProductB * creatProductB()
    {
        return (new ProductB2());
    }
};

void test_factory_abstract()
{
    Factory1 f1;
    auto pa1 = f1.creatProductA();
    auto pb1 = f1.creatProductB();
    pa1->showProduct();
    pb1->showProduct();

    Factory2 f2;
    auto pa2 = f2.creatProductA();
    auto pb2 = f2.creatProductB();
    pa2->showProduct();
    pb2->showProduct();
}
#endif

行为型-责任链模式

行为型-责任链模式

//行为型-责任链模式
#if 0&&4
class Request
{
public:
    virtual int getRequestType() = 0;
};

class Request_level1 :public Request
{
public:
    int getRequestType()
    {
        return 1;
    }
};

class Request_level2 :public Request
{
public:
    int getRequestType()
    {
        return 2;
    }
};

class Request_level3 :public Request
{
public:
    int getRequestType()
    {
        return 3;
    }
};

class Request_level4 :public Request
{
public:
    int getRequestType()
    {
        return 4;
    }
};

class Master
{
public:
    virtual void set_next_master(Master * next) = 0;
    virtual void handle_request(Request* req) = 0;
protected:
    Master * next_master;
};

class DM :public Master
{
public:
    void handle_request(Request* req)
    {
        if (is_in_office())
        {
            cout << "dm said ok,finish" << endl;
        }
        else
        {
            cout << "dm said not ok,finish" << endl;
        }
    }
    void set_next_master(Master * next)
    {
        next_master = NULL;
    }
    bool is_in_office()
    {
        //return true;
        return false;
    }
};

class PD :public Master
{
public:
    void handle_request(Request* req)
    {
        if (req->getRequestType() > 2)
        {
            if (next_master != nullptr)
            {
                cout << "pd not said ok,continu ..." << endl;
                next_master->handle_request(req);
            }
            else
            {
                cout << "pd not said ok,and next master is not in office,not ok ,finish" << endl;
            }
        }
        else
        {
            cout << "pd said ok,finish" << endl;
        }
    }
    void set_next_master(Master * next)
    {
        next_master = next;
    }
};

class PM :public Master
{
public:
    void handle_request(Request* req)
    {
        cout << "----------------------------" << endl;
        if (req->getRequestType()>1)
        {
            if (next_master != nullptr)
            {
                cout << "pm not said ok,continu ..." << endl;
                next_master->handle_request(req);
            }
            else
            {
                cout << "pm not said ok,and next master is not in office,not ok ,finish" << endl;
            }
        }
        else
        {
            cout << "pm said ok,finish" << endl;
        }
    }
    void set_next_master(Master * next)
    {
        next_master = next;
    }
};
void test_chain_of_responsibility()
{
    Request * req1 = new Request_level1();
    Request * req2 = new Request_level2();
    Request * req3 = new Request_level3();
    Request * req4 = new Request_level4();
    Master * pm = new PM();
    Master * pd = new PD();
    Master * dm = new DM();
    pm->set_next_master(pd);
    pd->set_next_master(dm);
    dm->set_next_master(nullptr);
    pm->handle_request(req1);
    pm->handle_request(req2);
    pm->handle_request(req3);
    pm->handle_request(req4);

    delete req1;
    req1 = nullptr;
    delete req2;
    req2 = nullptr;
    delete req3;
    req3 = nullptr;
    delete req4;
    req4 = nullptr;
    delete pm;
    pm = nullptr;
    delete pd;
    pd = nullptr;
    delete dm;
    dm = nullptr;
}
#endif

行为型-策略模式

行为型-策略模式

//行为型-策略模式
#if 0&&5
class Strategy
{
public:
    virtual void run() = 0;
};

class ConcreteStrategy1 :public Strategy
{
    void run()
    {
        cout << "run Strategy 1"<<endl;
    }
};

class ConcreteStrategy2 :public Strategy
{
    void run()
    {
        cout << "run Strategy 2" << endl;
    }
};

class ConcreteStrategy3 :public Strategy
{
    void run()
    {
        cout << "run Strategy 3" << endl;
    }
};

class Context
{
public:
    void run()
    {
        m_strategy->run();
    }

    void setStrategy(Strategy * s)
    {
        m_strategy = s;
    }
private:
    Strategy * m_strategy;
};

void test_strategy()
{
    Context ctx;
    Strategy * s1 = new ConcreteStrategy1();
    Strategy * s2 = new ConcreteStrategy2();
    Strategy * s3 = new ConcreteStrategy3();

    ctx.setStrategy(s1);
    ctx.run();
    ctx.setStrategy(s2);
    ctx.run();
    ctx.setStrategy(s3);
    ctx.run();
}
#endif

创建型-单例模式

创建型-单例模式

//创建型-单例模式
#if 0&&6
#include <mutex>
template<class T>
class Singleton
{
public:
    static T *getInstancePtr()
    {
        if (m_instance == nullptr)
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            if (m_instance == nullptr)
            {
                cout << "----init instance----" << endl;
                m_instance = new T();
            }
        }
        return m_instance;
    }

    static T & getInstance()
    {
        return *getInstancePtr();
    }

    static void releaseInstance()
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        if (m_instance)
        {
            delete m_instance;
            m_instance = nullptr;
        }
    }

    Singleton(){}
    ~Singleton(){}
    Singleton(const Singleton&) = delete;
    Singleton(Singleton&&) = delete;
    Singleton&operator=(const Singleton&) = delete;
    Singleton&operator=(Singleton&&) = delete;
private: 
    static std::mutex m_mutex;
    static T * m_instance;
};

template<class T>
T * Singleton<T>::m_instance = nullptr;

template<class T>
std::mutex Singleton<T>::m_mutex;



class TestClass :public Singleton<TestClass>
{
public:
    void runfun1()
    {
        cout << "runfun1" << endl;
    }
    void runfun2()
    {
        cout << "runfun2" << endl;
    }
};

#include <windows.h>
#include <thread>
void test_singleton()
{
    for (int i = 0; i < 10;++i)
    {
        std::thread th([](){
            Sleep(1000);
            Singleton<TestClass>::getInstance().runfun1();
            Singleton<TestClass>::getInstance().runfun2();
        });
        th.detach();
    }
    Sleep(3000);
}
#endif

结构型-外观模式

结构型-外观模式

//结构型-外观模式
//将一组复杂的操作封装成一个简单的操作,提供给外界。那么这个简单接口就是那组接口的外观(门面)
#if 0&&7
#include <iostream>
using namespace std;

// 语法分析子系统
class CSyntaxParser
{
public:
    void SyntaxParser()
    {
        cout << "Syntax Parser" << endl;
    }
};

// 生成中间代码子系统
class CGenMidCode
{
public:
    void GenMidCode()
    {
        cout << "Generate middle code" << endl;
    }
};

// 生成汇编代码子系统
class CGenAssemblyCode
{
public:
    void GenAssemblyCode()
    {
        cout << "Generate assembly code" << endl;
    }
};

// 链接生成可执行应用程序或库子系统
class CLinkSystem
{
public:
    void LinkSystem()
    {
        cout << "Link System" << endl;
    }
};

class Facade
{
public:
    void Compile()
    {
        CSyntaxParser syntaxParser;
        CGenMidCode genMidCode;
        CGenAssemblyCode genAssemblyCode;
        CLinkSystem linkSystem;
        syntaxParser.SyntaxParser();
        genMidCode.GenMidCode();
        genAssemblyCode.GenAssemblyCode();
        linkSystem.LinkSystem();
    }
};

// 客户端
void test_outface()
{
    Facade facade;
    facade.Compile();
}
#endif

行为型-观察者模式

行为型-观察者模式

//行为型-观察者模式
#if 0&&8
class Observer
{
public:
    virtual void update(const string & info) = 0;
};

class Subject
{
public:
    virtual void attachObserver(Observer * ob) = 0;
    virtual void detachObserver(Observer * ob) = 0;
    virtual void notify(const string & info) = 0;

    std::list<Observer *> listObserver;
};

class concreteObserver1 :public Observer
{
public:
    void update(const string & info)
    {
        cout << "concreteObserver1 do some thing, " << info << endl; 
    }
};

class concreteObserver2 :public Observer
{
public:
    void update(const string & info)
    {
        cout << "concreteObserver2 do some thing, " << info << endl;
    }
};

class concreteSubject :public Subject
{
    void attachObserver(Observer * ob)
    {
        listObserver.push_back(ob);
    }
    void detachObserver(Observer * ob)
    {
        listObserver.remove(ob);
    }
    void notify(const string & info)
    {
        std::list<Observer *>::iterator it = listObserver.begin();
        while (it != listObserver.end())
        {
            (*it)->update(info);
            ++it;
        }
    }
};

void test_observer()
{
    Subject * sub = new concreteSubject();
    Observer * ob11 = new concreteObserver1();
    Observer * ob12 = new concreteObserver1();
    Observer * ob21 = new concreteObserver2();
    Observer * ob22 = new concreteObserver2();
    sub->attachObserver(ob11);
    sub->attachObserver(ob12);
    sub->attachObserver(ob21);
    sub->attachObserver(ob22);

    sub->notify("haha xushuilong");

    sub->detachObserver(ob12);
    sub->detachObserver(ob22);

    sub->notify("heihei xujiahui");
}
#endif

结构型-桥接模式

结构型-桥接模式

//结构型-桥接模式
//桥接模式就是为了适应多个维度的变化而发生子类“爆炸”的情况
//将实现封装成抽象类,这样便可继承形成多种具体实现。
//这些具体实现(RealImplement)并不直接对外调用。
//而是通过一个桥接类(RealAbstract),对外提供接口。
#if 0&&9
class Implement
{
public:
    virtual void Implementation1() = 0;
    virtual void Implementation2() = 0;
};

class Abstract
{
public:
    Abstract(Implement * p) :impl(p){}
    virtual void operatation1() = 0;
    virtual void operatation2() = 0;
protected:
    Implement * impl;
};


class RealAbstract :public Abstract
{
public:
    RealAbstract(Implement * p) :Abstract(p){}
    void operatation1()
    {
        impl->Implementation1();
    }
    void operatation2()
    {
        impl->Implementation1();
        impl->Implementation2();
    }
};

class RealImplement :public Implement
{
    void Implementation1()
    {
        cout << "RealImplement::Implementation1" << endl;
    }
    void Implementation2()
    {
        cout << "RealImplement::Implementation2" << endl;
    }
};

void test_bridging()
{
    Implement* im = new RealImplement();
    Abstract* abs = new RealAbstract(im);
    abs->operatation1();
    abs->operatation2();
}
#endif

结构型-组合模式

结构型-组合模式

//结构型-组合模式(略)
//将对象组合成树形结构以表示“部分 - 整体”的层次结构。
//组合(Composite)模式使得用户对单个对象和组合对象的使用具有一致性。
#if 0&&10
class Component
{
public:
    Component(const string &name) :m_component_name(name){}
    virtual void addComponent(Component * comp) = 0;
    virtual void removeComponent(Component * comp) = 0;
    virtual void visitComponent() = 0;
protected:
    string m_component_name;
};

class Leaf :public Component
{
public:
    Leaf(const string &name) :Component(name){}
    void addComponent(Component * comp){}
    void removeComponent(Component * comp){}
    void visitComponent()
    {
        cout << "Leaf name="<<m_component_name << endl;
    }
};

class Composite :public Component
{
public:
    Composite(const string &name) :Component(name){}
    void addComponent(Component * comp){
        lt.push_back(comp);
    }
    void removeComponent(Component * comp){
        lt.remove(comp);
    }
    void visitComponent()
    {
        cout << "------------------1" << endl;
        cout << "Composite name=" << m_component_name << endl;
        for (auto item:lt)
        {
            item->visitComponent();
        }
        cout << "------------------2" << endl;
    }
private:
    list<Component *> lt;
};

void test_compose()
{
    Component * leaf11 = new Leaf("leaf11");
    Component * leaf12 = new Leaf("leaf12");
    Component * leaf13 = new Leaf("leaf13");
    Component * leaf14 = new Leaf("leaf14");
    Component * leaf15 = new Leaf("leaf15");

    Component * leaf21 = new Leaf("leaf21");
    Component * leaf22 = new Leaf("leaf22");
    Component * leaf23 = new Leaf("leaf23");
    Component * leaf24 = new Leaf("leaf24");

    Component * leaf31 = new Leaf("leaf31");
    Component * leaf32 = new Leaf("leaf32");
    Component * leaf33 = new Leaf("leaf33");
    Component * leaf34 = new Leaf("leaf34");

    Component * comp1 = new Composite("comp1");
    Component * comp2 = new Composite("comp2");
    Component * comp3 = new Composite("comp3");

    leaf11->visitComponent();
    leaf21->visitComponent();
    leaf31->visitComponent();

    comp1->addComponent(leaf11);
    comp1->addComponent(leaf12);
    comp1->addComponent(leaf13);
    comp1->addComponent(leaf14);
    comp1->addComponent(leaf15);

    comp2->addComponent(leaf21);
    comp2->addComponent(leaf22);
    comp2->addComponent(leaf23);
    comp2->addComponent(leaf24);

    comp3->addComponent(leaf31);
    comp3->addComponent(leaf32);
    comp3->addComponent(leaf33);
    comp3->addComponent(leaf34);

    comp1->visitComponent();
    comp2->visitComponent();
    comp3->visitComponent();

    comp1->removeComponent(leaf15);
    comp1->visitComponent();

    comp1->removeComponent(leaf15);
    comp1->visitComponent();
}
#endif

创建型-原型模式

创建型-原型模式

//创建型-原型模式
//注意深拷贝与浅拷贝的区别
#if 0&&11
//接口
class Prototype
{
public:
    Prototype(){}
    virtual ~Prototype(){}
    virtual Prototype * Clone() = 0;
};

//实现
class ConcretePrototype : public Prototype
{
public:
    ConcretePrototype() :m_counter(0){}
    virtual ~ConcretePrototype(){}

    //拷贝构造函数
    ConcretePrototype(const ConcretePrototype & rhs)
    {
        m_counter = rhs.m_counter;
    }

    //复制自身
    virtual ConcretePrototype * Clone()
    {
        //调用拷贝构造函数
        return new ConcretePrototype(*this);
    }

private:
    int m_counter;
};

void test_proto()
{
    //生成对像
    ConcretePrototype * conProA = new ConcretePrototype();

    //复制自身
    ConcretePrototype * conProB = conProA->Clone();

    delete conProA;
    conProA = NULL;

    delete conProB;
    conProB = NULL;
}
#endif

结构型-代理模式

结构型-代理模式

//结构型-代理模式
//在某些情况下,客户端直接访问目标对象可能不安全,或因其他原因而有意为之。
//此时需要会基于目标对象之上封装一个代理对象,以供客户端访问,从而达到间接访问目标对象的目的。
#if 0&&12
class Target
{
public:
    virtual void Request() = 0;
};
class ConcreteTarget :public Target 
{
public:
    void Request()
    {
        cout << "ConcreteTarget receive request" << endl;
    }
};
class Proxy
{
public:
    Proxy(Target * t) :target(t){}

    void Request()
    {
        target->Request();
    }
private:
    Target * target;
};

void test_proxy()
{
    Target * target = new ConcreteTarget();
    Proxy pro(target);
    pro.Request();
}

#endif

结构型-适配器模式

结构型-适配器模式

//结构型-适配器模式
#if 0&&13
class Target
{
public:
    virtual void func() = 0;
};
class Adaptee
{
public:
    void spec_func()
    {
        cout << "spec_func" << endl;
    }
};
class Adapter :public Target
{
public:
    Adapter(Adaptee * ad){
        m_adaptee = ad;
    }
    void func()
    {
        m_adaptee->spec_func();
    }
    Adaptee * m_adaptee;
};

void test_adapter()
{
    Adaptee ade;
    Target *targetObj = new Adapter(&ade);
    targetObj->func();

    delete targetObj;
    targetObj = NULL;
}
#endif

结构型-装饰模式

结构型-装饰模式

//结构型-装饰模式
//动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
//装饰模式是通过把复杂的功能简单化,分散化,然后再运行期间,根据需要来动态组合的这样一个模式。
//它使得我们可以给某个对象而不是整个类添加一些功能。
#if 0&&14
class Component
{
public:
    virtual void operate()
    {
        cout << "I am Component no Decorator" << endl;
    }
};

class Decorator :public Component
{
public:
    Decorator(Component * p)
        :m_component(p)
    {
    
    }
    void operate()
    {
        if (m_component)
        {
            m_component->operate();
        }
    }
protected:
    Component * m_component;
};


class RealDecorator1 :public Decorator
{
public:
    RealDecorator1(Component * p) :Decorator(p){}
    void operate()
    {
        AddedBehavior();
        m_component->operate();
    }
    void  AddedBehavior()
    {
        cout << "This is added behavior 1." << endl;
    }
};

class RealDecorator2 :public Decorator
{
public:
    RealDecorator2(Component * p) :Decorator(p){}
    void operate()
    {
        AddedBehavior();
        m_component->operate();
    }
    void  AddedBehavior()
    {
        cout << "This is added behavior 2." << endl;
    }
};

void test_decorator()
{
    Component * pcomp = new Component();
    Component *deco1 = new RealDecorator1(pcomp);
    Component *deco2 = new RealDecorator2(deco1);
    Component *deco3 = new RealDecorator2(deco2);
    Component *deco4 = new RealDecorator2(deco3);
    pcomp->operate();
    deco1->operate();
    deco2->operate();
    deco3->operate();
    deco4->operate();
    SAFE_DELETE(pcomp);
    assert(!pcomp);
    SAFE_DELETE(deco1);
    SAFE_DELETE(deco2);
}
#endif

行为型-模板方法模式

行为型-模板方法模式

//行为型-模板方法模式
#if 0&&15

#endif

行为型-备忘录模式

行为型-备忘录模式

//行为型-备忘录模式
#if 0&&16

#endif

行为型-状态模式

行为型-状态模式

//行为型-状态模式
//类中存在大量的结构类似的分支语句,变得难以维护和理解。
//状态模式消除了分支语句,就像工厂模式消除了简单工厂模式的分支语句一样,
//将状态处理分散到各个状态子类中去,每个子类集中处理一种状态,
//这样就使得状态的处理和转换清晰明确。
#if 0&&17
class AbstractState
{
public:
    virtual void doState() = 0;
};

class ConcreteState1 :public AbstractState
{
    void doState()
    {
        cout << "ConcreteState1 do state" << endl;
    }
};

class ConcreteState2 :public AbstractState
{
    void doState()
    {
        cout << "ConcreteState2 do state" << endl;
    }
};

class Context
{
public:
    Context(AbstractState * s) :m_state(s){
    
    }
    void RequestByState()
    {
        if (m_state)
        {
            m_state->doState();
        }
    }
    void Request(AbstractState * state)
    {
        if (state)
        {
            state->doState();
        }
    }
    void setState(AbstractState * state)
    {
        m_state = state;
    }
private: 
    AbstractState * m_state;
};

void test_state()
{
    AbstractState * state1 = new ConcreteState1();
    AbstractState * state2 = new ConcreteState2();
    Context ctx(state1);
    ctx.RequestByState();
    ctx.setState(state2);
    ctx.RequestByState();

    ctx.Request(state1);
    ctx.Request(state2);
}
#endif

行为型-模板模式

行为型-模板模式

//行为型-模板模式
#if 0&&18

#endif

行为型-中介者模式

行为型-中介者模式

//行为型-中介者模式
//用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,
//从而使其耦合松散,而且可以独立地改变它们之间的交互。
#if 0&&19
class Mediator;
//注意:当采用某个类前置声明时,指针引用了该类的其他类的函数只能在类外实现。
class Person
{
public:
    Person(Mediator * m) :medi(m){}
    virtual void send_to_media(const string & msg) = 0;
    virtual void handle_msg(const string & msg) = 0;
    virtual const string getName() = 0;
protected:
    Mediator * medi;
};

class PersonA :public Person
{
public:
    PersonA(Mediator * m) :Person(m){}
    void send_to_media(const string & msg);
    const string getName()
    {
        return "PersonA";
    }
    void handle_msg(const string & msg)
    {
        cout << "PersonA handle_msg:"<<msg << endl;
    }
};

class PersonB :public Person
{
public:
    PersonB(Mediator * m) :Person(m){}
    void send_to_media(const string & msg);
    const string getName()
    {
        return "PersonB";
    }
    void handle_msg(const string & msg)
    {
        cout << "PersonB handle_msg:" << msg << endl;
    }
};

class Mediator
{
public:
    void resend_to_handle(const string & msg, Person* from)
    {
        for (auto &item : vt_person)
        {
            if (from->getName() != item->getName())
            {
                item->handle_msg(msg);
            }
        }
    }
    void addPerson(Person* p)
    {
        vt_person.push_back(p);
    }
private:
    vector<Person*> vt_person;
};

void PersonA::send_to_media(const string & msg)
{
    medi->resend_to_handle(msg, this);
}

void PersonB::send_to_media(const string & msg)
{
    medi->resend_to_handle(msg, this);
}
void test_mediator()
{
    Mediator * medi = new Mediator();
    Person * pa1 = new PersonA(medi);
    Person * pa2 = new PersonA(medi);
    Person * pb1 = new PersonB(medi);
    Person * pb2 = new PersonB(medi);
    medi->addPerson(pa1);
    medi->addPerson(pa2);
    medi->addPerson(pb1);
    medi->addPerson(pb2);

    pa1->send_to_media("I am pa1");
    pa2->send_to_media("I am pa2");
    pb1->send_to_media("I am pb1");
    pb2->send_to_media("I am pb2");
}
#endif
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值