行为型模型之中介者模式

#include<iostream>
#include<string>
using namespace std;

class Admierter;
class Person
{
public:
	Person(string name, int sex, int condition, Admierter *admierter)
	{
		m_name = name;
		m_sex = sex;
		m_condition = condition;
		m_admierter = admierter;
	}
	virtual void getPartner(Person*p) = 0;
	string getName()
	{
		return m_name;
	}

	int getSex()
	{
		return m_sex;
	}

	int getCondition()
	{
		return m_condition;
	}
protected:
	string m_name;
	int m_sex;
	int m_condition;
	Admierter *m_admierter;
};

class Admierter
{
public:
	void setWoman(Person*p1)
	{
		woman = p1;
	}

	void setMan(Person*p2)
	{
		man = p2;
	}

	void getPartner()//由中介进行判断是否相配
	{
		if (woman->getSex() == man->getSex())
		{
			cout << "同性恋" << endl;
		}
		if (woman->getCondition() == man->getCondition())
		{
			cout << woman->getName() << " 和 " << man->getName() << "绝配!" << endl;
		}
		else
		{
			cout << woman->getName() << " 和 " << man->getName() << "不相配" << endl;
		}
	}
private:
	Person *woman;
	Person *man;
};

class Woman :public Person
{
public:
	Woman(string name, int sex, int condition, Admierter *admierter) :Person(name, sex, condition,admierter)
	{

	}
	virtual void getPartner(Person*p)
	{
		m_admierter->setWoman(this);
		m_admierter->setMan(p);
		m_admierter->getPartner();
	}
};

class Man :public Person
{
public:
	Man(string name, int sex, int condition, Admierter *admierter) :Person(name, sex, condition, admierter)
	{

	}
	virtual void getPartner(Person*p)
	{
		m_admierter->setWoman(p);
		m_admierter->setMan(this);
		m_admierter->getPartner();
	}
};

void main()
{
	Admierter *admierter = new Admierter;
	Woman *xiaoyu = new Woman("小雨", 2, 3, admierter);
	Man *xiaowang = new Man("小王", 1, 2, admierter);
	Man *xiaoliu = new Man("小刘", 1, 3, admierter);
	xiaoyu->getPartner(xiaowang);
	xiaoyu->getPartner(xiaoliu);

	xiaowang->getPartner(xiaoliu);

}

运行结果:



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页