[设计模式]迪米特法则

Posted Wecccccccc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[设计模式]迪米特法则相关的知识,希望对你有一定的参考价值。

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

类中的成员属性和成员方法,如果不需要对外暴露,就不要设成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;
}

测试结果:

以上是关于[设计模式]迪米特法则的主要内容,如果未能解决你的问题,请参考以下文章

设计模式之美——DRY原则 和 迪米特法则

设计模式之美——DRY原则 和 迪米特法则

深入浅出设计模式——迪米特法则

设计模式六大原则:迪米特法则

10设计模式六大原则——迪米特法则

面向对象设计原则 迪米特法则(Law of Demeter)