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

时间:2022-12-03 15:19:07

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#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");
}

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

原文链接:https://blog.csdn.net/wwxy1995/article/details/85084040