欢迎来到代码驿站!

C代码

当前位置:首页 > 软件编程 > C代码

C++设计模式迪米特法则实例

时间:2021-09-10 10:14:04|栏目:C代码|点击:

迪米特法则(Law of Demeter)又叫作最少知识原则(Least Knowledge Principle 简写LKP),就是说一个对象应当对其他对象有尽可能少的了解,不和陌生人说话。英文简写为: LoD.

类的设计接口尽量封装完善,让外部直接调用

#include<iostream>
#include<string>
#include<vector>
using namespace std;
 
class AbstractBuilding
{
public:
 virtual void sale() = 0;
 virtual string getQuality() = 0;
 
};
 
class BuildingA :public AbstractBuilding
{
public:
 
 BuildingA()
 {
 mQulity = "高品质";
 }
 
 virtual void sale()
 {
 cout << "楼盘A" << mQulity << "被售卖!" << endl;
 }
 
 virtual string getQuality()
 {
 return mQulity;
 }
 
public:
 string mQulity;
};
 
 
class BuildingB :public AbstractBuilding
{
public:
 
 BuildingB()
 {
 mQulity = "低品质";
 }
 
 virtual void sale()
 {
 cout << "楼盘B" << mQulity << "被售卖!" << endl;
 }
 
 virtual string getQuality()
 {
 return mQulity;
 }
 
public:
 string mQulity;
};
 
// 中介类
class Mediator
{
public:
 Mediator()
 {
 AbstractBuilding* building = new BuildingA;
 vBuilding.push_back(building);
 building = new BuildingB;
 vBuilding.push_back(building);
 }
 
 // 对外提供接口
 AbstractBuilding* findMyBuilding(string quality)
 {
 for (vector<AbstractBuilding*>::iterator it = vBuilding.begin();
  it != vBuilding.end(); it++)
 {
  if ((*it)->getQuality() == quality)
  {
  return *it;
  }
 }
 
 return NULL;
 }
 
 ~Mediator()
 {
 for (vector<AbstractBuilding*>::iterator it = vBuilding.begin();
  it != vBuilding.end(); it++)
 {
  if (*it != NULL)
  delete *it;
 }
 }
public:
 vector<AbstractBuilding*> vBuilding;
};
 
 
void test01()
{
 Mediator* mediator = new Mediator;
 
 AbstractBuilding* building = mediator->findMyBuilding("低品质");
 
 if (building != NULL)
 {
 building->sale();
 
 }
 else
 {
 cout << "没有符号条件的楼盘" << endl;
 }
 
}
 
int main()
{
 test01();
 system("pause");
}

上一篇:C++实现LeetCode(52.N皇后问题之二)

栏    目:C代码

下一篇:C语言实现简易通讯录

本文标题:C++设计模式迪米特法则实例

本文地址:http://www.codeinn.net/misctech/173914.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有