//
// main.cpp
// meditor_pattern
//
// Created by apple on 2019/3/12.
// Copyright © 2019年 apple. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
class IPerson;
class IMediator
{
protected:
IPerson **A;//卖家
IPerson **B;///买家
public:
IMediator(IPerson **saler, IPerson **buyer) {A = saler; B = buyer;}
virtual IMediator *change_saler_or_buyer(IPerson **saler, IPerson **buyer) = 0;
virtual void sale(int num) = 0;
virtual void buy(int num) = 0;
virtual ~IMediator() {}
};
class IPerson
{
public:
int num;//所拥有的房屋数量
string name;//姓名
virtual void sale_house(int, IMediator *) = 0;//卖房者通过中介卖房
virtual void buy_house(int, IMediator *) = 0;//买房者通过中介买房
virtual ~IPerson() {}
};
class Saler:public IPerson
{
public:
Saler(string name) {this->name = name; this->num = 5;} //卖房者初始拥有5套房
void sale_house(int num, IMediator *mediator) {if(this->num-num>=0){this->num-=num;mediator->sale(num);}else{cout<<"not enough"<<endl;}}
void buy_house(int num, IMediator *mediator){}//针对卖房者,未做具体实现
};
class Buyer:public IPerson
{
public:
Buyer(string name){this->name = name; this->num = 0;}//买房者初始拥有0套房
void sale_house(int num, IMediator *mediator){}//针对买房者,未做具体实现
void buy_house(int num, IMediator *mediator){this->num+=num;mediator->buy(num);}
};
class Mediator: public IMediator
{
public:
Mediator(IPerson **saler, IPerson **buyer):IMediator(saler, buyer) {}
IMediator *change_saler_or_buyer(IPerson **saler, IPerson **buyer){A = saler; B = buyer; return this;}
void sale(int num){(*B)->num += num;}
void buy(int num){(*A)->num -= num;}
};
int main(int argc, const char * argv[]) {
IPerson *saler = new Saler("saler");
IPerson *buyer = new Buyer("buyer");
IMediator *mediator = new Mediator(&saler, &buyer);
saler->sale_house(2, mediator);//saler通过中介者mediator卖了2套房,这两套房卖给了buyer
//对于saler,他知道自己的信息,同时还知道中介提供了买/卖房接口,对于中介如何卖房,saler并不清楚;
buyer->buy_house(1, mediator);//
cout<<saler->name<<":"<<saler->num<<endl;
cout<<buyer->name<<":"<<buyer->num<<endl;
delete mediator;
delete saler;
delete buyer;
return 0;
}
saler:2
buyer:3
Program ended with exit code: 0
网友评论