3.13 以类取代类型码
【1】源代码
1 #include <QString> 2 #include <QDebug> 3 4 class Student 5 { 6 public: 7 Student(int id, QString name, int status) 8 : m_nID(id) 9 , m_name(name) 10 , m_status(status) 11 {} 12 13 int getId() 14 { 15 return m_nID; 16 } 17 void setId(int id) 18 { 19 m_nID = id; 20 } 21 22 QString getName() 23 { 24 return m_name; 25 } 26 void setName(QString name) 27 { 28 m_name = name; 29 } 30 31 int getStatus() 32 { 33 return m_status; 34 } 35 void setStatus(int status) 36 { 37 m_status = status; 38 } 39 40 QString toString() 41 { 42 return QString("Student [id = %1, name = %2, status = %3]") 43 .arg(QString::number(m_nID)).arg(m_name).arg(QString::number(m_status)); 44 } 45 46 public: 47 static const int INVALID; 48 static const int VALID; 49 50 private: 51 int m_nID; 52 QString m_name; 53 int m_status; 54 }; 55 56 const int Student::INVALID = 0; 57 const int Student::VALID = 1; 58 59 void main() 60 { 61 Student *pStudent = new Student(1, "张三", Student::VALID); 62 qDebug() << pStudent->toString(); 63 } 64 65 // run out: 66 /* 67 * "Student [id = 1, name = 张三, status = 1]" 68 */
【2】以类取代类型码
1 #include <QString> 2 #include <QDebug> 3 4 class StatusCode 5 { 6 public: 7 StatusCode(int nCode) 8 : m_nCode(nCode) 9 {} 10 11 int getCode() 12 { 13 return m_nCode; 14 } 15 16 void setCode(int code) 17 { 18 m_nCode = code; 19 } 20 21 QString toString() 22 { 23 return QString("StatusCode [code = %1]").arg(QString::number(m_nCode)); 24 } 25 26 private: 27 int m_nCode; 28 }; 29 30 class Student 31 { 32 public: 33 Student(int id, QString name, StatusCode status) 34 : m_nID(id) 35 , m_name(name) 36 , m_status(status) 37 {} 38 39 int getId() 40 { 41 return m_nID; 42 } 43 void setId(int id) 44 { 45 m_nID = id; 46 } 47 48 QString getName() 49 { 50 return m_name; 51 } 52 void setName(QString name) 53 { 54 m_name = name; 55 } 56 57 StatusCode getStatus() 58 { 59 return m_status; 60 } 61 void setStatus(StatusCode status) 62 { 63 m_status = status; 64 } 65 66 QString toString() 67 { 68 return QString("Student [id = %1, name = %2, status = %3]") 69 .arg(QString::number(m_nID)).arg(m_name).arg(m_status.toString()); 70 } 71 72 private: 73 int m_nID; 74 QString m_name; 75 StatusCode m_status; 76 }; 77 78 void main() 79 { 80 Student *pStudent = new Student(1, "张三", StatusCode(1)); 81 qDebug() << pStudent->toString(); 82 } 83 84 // run out: 85 /* 86 * "Student [id = 1, name = 张三, status = StatusCode [code = 1]]" 87 */
【3】总结
类中有一个数值类型码,但它并不影响类的行为。以一个新的类替换该数值类型码。
在使用Replace Type Code with Class (以类取代类型码)之前,你应该先考虑类型码的其他替换方式。
只有当类型码是纯粹数据时(也就是类型码不会在switch语句中引起行为变化时),你才能以类来取代它。
更重要的是:任何switch语句都应该运用Replace Conditional with Polymorphism (以多态取代条件表达式)去掉。
为了进行那样的重构,你首先必须运用 Replace Type Code with Subclass (以子类取代类型码)或Replace Type Code with State/Strategy (以状态策略取代类型码),把类型码处理掉。
Good Good Study, Day Day Up.
顺序 选择 循环 总结