The Mediator Pattern of Design Patterns (Mediator)

The mediator pattern is a design pattern for data interaction. The core of the pattern is a mediator object, which is responsible for coordinating different data requests between a series of objects, which become colleague classes. For example, real estate agents (just don't want to mention it), those who buy houses and sell houses, and those who rent houses and rent them all go to the real estate agent to register. If there is a house for sale, the buyer will be notified to buy a house, and if there is a renter, the renter will be notified to rent a house. All things are notified and converted through intermediaries, thus forming a typical star structure. Speaking of star structure, isn't the switch router in the network a big intermediary.

effect

The Mediator pattern wraps the way a series of objects interact so that these objects don't have to interact explicitly with each other. so that they can be loosely coupled. When the role of some objects changes, it will not immediately affect the role of other objects. It is guaranteed that these roles can be changed independently of each other.

class view

accomplish

The intermediary model is the auction house role, responsible for the coordination of buyers, sellers and currency conversion, where Indian buyers and French buyers want to auction things from US sellers, India uses rupees, France uses US dollars, and the United States uses All bids are settled in U.S. dollars; this requires the auction house to coordinate price conversion, auction bidding, etc.

//头文件mediator.h
#include <string>

class  Mediator;
 
class Colleage //同事类
{
public:
    Colleage(Mediator* md);
protected:
    Mediator *m_mediator;
};

class IndianBuyer: public Colleage
{
public:
    IndianBuyer(Mediator* md);
    void setTotalMoney(float fall);
    int Purchase(float bid);
private:
    float m_total_money; //买家的心理价位
};

class FrenchBuyer: public Colleage
{
public:
    FrenchBuyer(Mediator* md);
    void setTotalMoney(float fall);
    int Purchase(float bid);
private:
    float m_total_money;
};

class AmericanSeller: public Colleage
{
public:
    AmericanSeller(Mediator* md);
    void SetWantPrice(float price);
    bool IsBidAccept(float bidInDollars);
private:
    float m_priceInDollars; //卖家的心理价位
};

class DollorConver: public Colleage
{
public:
    DollorConver(Mediator* md);
    float ConverToDollars(float bid, std::string strName);
private:
    float ConverRupeetoDollar(float bid);
    float ConverEurotoDollar(float bid);
private:
    float dollor_unit; //美元换算比例
    float euro_unit;  //欧元换算比例
    float rupee_unit;//卢比换算比例
};

class Mediator
{
public:
    Mediator();
    void RegisterIndianBuyer(IndianBuyer* buyer);
    void RegisterFrenchBuyer(FrenchBuyer* buyer);
    void RegisterAmericanSeller(AmericanSeller* seller);
    void RegisterDollorConver(DollorConver* conver);
    bool placeBid(float bid,std::string strName);
private:
    IndianBuyer* m_pIndian;
    FrenchBuyer* m_pFrench;
    AmericanSeller* m_pAmerican;
    DollorConver* m_pConver;

};

mediator.cpp

#include <iostream>
#include "mediator.h"
using namespace std;

Colleage::Colleage(Mediator* md):m_mediator(md)
{
}
IndianBuyer::IndianBuyer(Mediator* md):Colleage(md),m_total_money(-1){
    m_mediator->RegisterIndianBuyer(this);
}
void IndianBuyer::setTotalMoney(float fall)
{
    m_total_money = fall;
}
int IndianBuyer::Purchase(float bid)
{
    //价格合适就出价一次
    if (m_total_money<0 || bid<= m_total_money)
    {
       return (int)m_mediator->placeBid(bid,"RUPEE"); 
    }
    else
    {
        return 2;//价格太高了  不要啦
    }
    
}

FrenchBuyer::FrenchBuyer(Mediator* md):Colleage(md),m_total_money(-1){
    m_mediator->RegisterFrenchBuyer(this);
}
void FrenchBuyer::setTotalMoney(float fall)
{
    m_total_money = fall;
}
int FrenchBuyer::Purchase(float bid)
{
    if (m_total_money<0 || bid<= m_total_money)
    {
       return (int)m_mediator->placeBid(bid,"EURO"); 
    }
    else
    {
        return 2;
    }
    
}

AmericanSeller::AmericanSeller(Mediator* md):Colleage(md),m_priceInDollars(0){
    m_mediator->RegisterAmericanSeller(this);
}
void AmericanSeller::SetWantPrice(float price)
{
    m_priceInDollars = price;
}
bool AmericanSeller::IsBidAccept(float bidInDollars)
{
    if (bidInDollars>=m_priceInDollars)
    {
       //当遇到价格增长时记录最高的价格,没有人超过这个价格就按照这个价格出售
        m_priceInDollars = bidInDollars;
        return true;
    }
    return false;
}

DollorConver::DollorConver(Mediator* md):Colleage(md)
,dollor_unit(1.0),euro_unit(0.7),rupee_unit(45.0){
    m_mediator->RegisterDollorConver(this);
}
float DollorConver::ConverToDollars(float bid, std::string strName)
{
    if (strName.compare("RUPEE")==0)
    {
        return ConverRupeetoDollar(bid);
    }
    else
    {
        return ConverEurotoDollar(bid);
    }
}
float DollorConver::ConverRupeetoDollar(float bid)
{
    return bid*(dollor_unit/rupee_unit);
}
float DollorConver::ConverEurotoDollar(float bid)
{
    return bid*(dollor_unit/euro_unit);
}


Mediator::Mediator():m_pIndian(NULL),m_pFrench(NULL)
,m_pAmerican(NULL),m_pConver(NULL){

}
void Mediator::RegisterIndianBuyer(IndianBuyer* buyer)
{
    m_pIndian = buyer;
}
void Mediator::RegisterFrenchBuyer(FrenchBuyer* buyer)
{
    m_pFrench = buyer;
}
void Mediator::RegisterAmericanSeller(AmericanSeller* seller)
{
    m_pAmerican = seller;
}
void Mediator::RegisterDollorConver(DollorConver* conver)
{
    m_pConver = conver;
}
bool Mediator::placeBid(float bid,std::string strName)
{
    float dollars =  m_pConver->ConverToDollars(bid,strName);
    return m_pAmerican->IsBidAccept(dollars);
}


int main(int argc,char *argv[])
{
    Mediator mediatior;

    IndianBuyer indian(&mediatior);
    FrenchBuyer french(&mediatior);
    AmericanSeller american(&mediatior);
    DollorConver conver(&mediatior);
    
    indian.setTotalMoney(6000);
    french.setTotalMoney(100);

    american.SetWantPrice(50);
    
    int  nIndian = 0;
    int  nFrench = 0;
    float IndianBid = 2000;
    float FrenchBid = 30;
    //一轮一轮进行出价,当有一个出不起的时候,就结束竞价。
    while(nIndian+nFrench<=2)
    {
        do{
            nIndian = indian.Purchase(IndianBid);
            IndianBid+=100;
            if (nIndian == 1)
            {
                cout<<"indian purchase : "<< IndianBid <<endl;
            }
            
        }
        while(nIndian==0);

        do{
            nFrench = french.Purchase(FrenchBid);
            FrenchBid+=1.5;
            if (nFrench == 1)
            {
                cout<<"french purchase : "<< FrenchBid <<endl;
            }
        }
        while(nFrench==0);

    }

    return 0;

}

When we start any product development, there will always be some classes. These classes will use the development results of previous products. With the increase of functions, the logic will become more complex. We will add more classes to interact with the previous classes. role, know that it is difficult to maintain all the code. This is what the mediator pattern is concerned with, it makes the code easier to maintain. It enables loose coupling between classes. Only the mediator class knows all the classes, and other classes only need to interact with the mediator. Of course, more centralized control will also bring about a huge center, and it is necessary to avoid excessive integration.

Application scenarios

  1. A group of objects uses standard communication methods, but the overall communication connections are very complex, and the resulting interdependent structure makes the system difficult to structure and understand;
  2. Objects are difficult to reuse due to communication and mutual references between objects.
  3. Behavior distributed among pairs of classes can be uniformly customized without creating too many subclasses.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325012238&siteId=291194637