欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

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

来源:本站原创|时间:2020-01-10|栏目: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");
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

上一篇:OpenCV霍夫变换(Hough Transform)直线检测详解

栏    目:C语言

下一篇:C++使用模板实现单链表(类外实现)

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

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/559.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

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

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有