[设计模式]迪米特法则

迪米特法则 又叫最少知识法则

类中的成员属性和成员方法,如果不需要对外暴露,就不要设成public。

代码如下:

#include <iostream>
#include <string>
using namespace std;class AbstractBuilding
{
public:virtual void sale() = 0;
};class BuildingA :public AbstractBuilding
{
public:BuildingA():quilty("高品质"){}virtual void sale(){cout << "楼盘A" << quilty << "被售卖!" << endl;}string quilty;
};class BuildingB :public AbstractBuilding
{
public:BuildingB() :quilty("低品质") {}virtual void sale(){cout << "楼盘B" << quilty << "被售卖!" << endl;}string quilty;
};void test01()
{BuildingA *ba = new BuildingA;if (ba->quilty == "低品质"){ba->sale();}BuildingB *bb = new BuildingB;if (bb->quilty == "低品质"){bb->sale();}
}int main()
{test01();return 0;
}

测试结果:

在这里插入图片描述

迪米特法则
代码如下:

#include <iostream>
#include <string>
#include <vector>
using namespace std;class AbstractBuilding
{
public:virtual void sale() = 0;virtual string getQuilty() = 0;
};class BuildingA :public AbstractBuilding
{
public:BuildingA():quilty("高品质"){}virtual void sale(){cout << "楼盘A" << quilty << "被售卖!" << endl;}virtual string getQuilty(){return quilty;}
private:string quilty;
};class BuildingB :public AbstractBuilding
{
public:BuildingB() :quilty("低品质") {}virtual void sale(){cout << "楼盘B" << quilty << "被售卖!" << endl;}virtual string getQuilty(){return quilty;}private:string quilty;
};//中介类
class Mediator {
public:Mediator(){AbstractBuilding *building = new BuildingA;vBuilding.push_back(building);building = new BuildingB;vBuilding.push_back(building);}~Mediator(){for (vector<AbstractBuilding*>::iterator it = vBuilding.begin(); it != vBuilding.end(); it++){if (*it != nullptr){delete *it;}}}//对外提供接口AbstractBuilding *findMyBuilding(string quality){for (vector<AbstractBuilding*>::iterator it = vBuilding.begin(); it != vBuilding.end(); it++){if ((*it)->getQuilty()==quality){return *it;}}return nullptr;}vector<AbstractBuilding*> vBuilding;};void test01()
{Mediator *mediator = new Mediator;//优点:用户不用跟具体楼盘打交道AbstractBuilding * building = mediator->findMyBuilding("高品质");if (building != nullptr){building->sale();}else{cout << "没有符合条件的楼盘" << endl;}
}int main()
{test01();return 0;
}

测试结果:

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注