3.16 以字段取代子类

【1】原代码

 1 class Person
 2 {
 3 public:
 4     virtual bool isMale() = 0;
 5     virtual char getCode() = 0;
 6 };
 7 
 8 class Male : public Person
 9 {
10 public:
11     bool isMale() { return true; }
12     char getCode() { return 'M';  }
13 };
14 
15 class FeMale : public Person
16 {
17 public:
18     bool isMale() { return false; }
19     char getCode() { return 'F'; }
20 };

【2】以字段取代子类

 1 class Person
 2 {
 3 public:
 4     static Person* createMale()
 5     {
 6         return (new Person(true, 'M'));
 7     }
 8     static Person* createFeMale()
 9     {
10         return (new Person(false, 'F'));
11     }
12 
13     bool isMale() { return m_bMale;  }
14     char getCode() { return m_sChar; }
15 
16 protected:
17     Person(bool bMale, char sChar)
18         : m_bMale(bMale)
19         , m_sChar(sChar)
20     {}
21 
22 private:
23     bool m_bMale;
24     char m_sChar;
25 };

【3】总结

各个子类的唯一差别只在”返回常量数据“的函数身上。修改这些函数,使它们返回超类中的某个(新增)字段,然后销毁子类。

 

Good Good Study, Day Day Up.

顺序 选择 循环 总结

posted @ 2017-08-15 10:32  kaizenly  阅读(334)  评论(0编辑  收藏  举报
打赏