2.5 隐藏委托关系
【1】源代码
1 #include <QString> 2 3 class Department; 4 class Person 5 { 6 public: 7 QString getName() 8 { 9 return m_name; 10 } 11 void setName(QString name) 12 { 13 m_name = name; 14 } 15 16 Department* get_department() 17 { 18 return m_department; // 获取部门对象 19 } 20 21 void set_department(Department *department) 22 { 23 m_department = department; 24 } 25 26 private: 27 QString m_name; 28 Department *m_department; 29 }; 30 31 class Department 32 { 33 public: 34 QString getCode() 35 { 36 return m_code; 37 } 38 void setCode(QString code) 39 { 40 m_code = code; 41 } 42 Person get_manager() 43 { 44 return m_manager; // 获取经理人 45 } 46 void set_manager(Person manager) 47 { 48 m_manager = manager; 49 } 50 51 private: 52 QString m_code; 53 Person m_manager; 54 }; 55 56 int main(int argc, char *argv[]) 57 { 58 QCoreApplication a(argc, argv); 59 60 Person person; 61 QString strName = person.get_department()->get_manager().getName(); // 客户端 62 // 这样的编码对客户暴露了Department的工作原理,于是客户知道:Department用以追踪"经理"这条信息。 63 64 return a.exec(); 65 }
【2】隐藏委托关系
1 class Person 2 { 3 public: 4 // 如果对客户隐藏Department,可以减少耦合。为了到达预期的目的,在Person中建立一个简单的委托函数。 5 Person getManager() 6 { 7 return m_department->get_manager(); // 隐藏委托类 8 } 9 10 QString getName() 11 { 12 return m_name; 13 } 14 void setName(QString name) 15 { 16 m_name = name; 17 } 18 19 Department* get_department() 20 { 21 return m_department; // 获取部门对象 22 } 23 24 void set_department(Department *department) 25 { 26 m_department = department; 27 } 28 29 private: 30 QString m_name; 31 Department *m_department; 32 }; 33 34 class Department 35 { 36 public: 37 QString getCode() 38 { 39 return m_code; 40 } 41 void setCode(QString code) 42 { 43 m_code = code; 44 } 45 Person get_manager() 46 { 47 return m_manager; // 获取经理人 48 } 49 void set_manager(Person manager) 50 { 51 m_manager = manager; 52 } 53 54 private: 55 QString m_code; 56 Person m_manager; 57 }; 58 59 int main(int argc, char *argv[]) 60 { 61 QCoreApplication a(argc, argv); 62 63 Person person; 64 QString strName = person.getManager().getName(); // 客户端调用方式 65 66 return a.exec(); 67 }
【3】总结
客户通过一个委托类来调用另一个对象。
在服务类上建立客户所需的所有函数,用以隐藏委托关系。
Good Good Study, Day Day Up.
顺序 选择 循环 总结