### Replace Type Code with State/Strategy(以State/strategy 取代型別碼)
你有一個type code ,它會影響class 的行為,但你無法使用subclassing。
以state object (專門用來描述狀態的對象)取代type code 。

**動機(Motivation)**
本項重構和Replace Type Code with Subclasses 很相似,但如果「type code 的值在對象生命期中發生變化」或「其他原因使得宿主類不能被subclassing 」,你也可以使用本重構。本重構使用State 模式或Stategy 模式[Gang of Four]。
State 模式和Stategy 模式非常相似,因此無論你選擇其中哪一個,重構過程都是相同的。「選擇哪一個模式」并非問題關鍵所在,你只需要選擇更適合特定情境的模式就行了。如果你打算在完成本項重構之后再以 Replace Conditional with Polymorphism 簡化一個算法,那么選擇Stategy 模式比較合適;如果你打算搬移與狀態相關(state-specific)的數據,而且你把新建對象視為一種變遷狀態 (changing state),就應該選擇使用State 模式。
**作法(Mechanics)**
- 使用Self-encapsulate Field 將type code 自我封裝起來。
- 新建一個class ,根據type code 的用途為它命名。這就是一個state object。
- 為這個新建的class 添加subclass ,每個subclass 對應一種type code 。
- 比起逐一添加,一次性加入所有必要的subclass 可能更簡單些。
- 在superclass 中建立一個抽象的查詢函數(abstract query ),用以返回type code 。 在每個subclass 中覆寫該函數,返回確切的type code 。
- 編譯。
- 在source class 中建立一個值域,用以保存新建的state object。
- 調整source class 中負責查詢type code 的函數,將查詢動作轉發給state object 。
- 調整source class 中「為type code 設值」的函數,將一個恰當的state object subclass 賦值給「保存state object」的那個值域。
- 編譯,測試。
**范例(Example)**
和上一項重構一樣,我仍然使用這個既無聊又弱智的「雇員丨薪資」例子。同樣地, 我以Employee 表示「雇員」:
~~~
class Employee {
private int _type;
static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
Employee (int type) {
_type = type;
}
~~~
下面的代碼展示使用這些type code 的條件式:
~~~
int payAmount() {
switch (_type) {
case ENGINEER:
return _monthlySalary;
case SALESMAN:
return _monthlySalary + _commission;
case MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
~~~
假設這是一家激情四溢、積極進取的公司,他們可以將表現出色的工程師擢升為經理。因此,對象的type code 是可變的,所以我不能使用subclassing 方式來處理type code 。和以前一樣,我的第一步還是使用Self Encapsulate Field 將表示type code 的值域自我封裝起來:
~~~
Employee (int type) {
setType (type);
}
int getType() {
return _type;
}
void setType(int arg) {
_type = arg;
}
int payAmount() {
switch (getType()) {
case ENGINEER:
return _monthlySalary;
case SALESMAN:
return _monthlySalary + _commission;
case MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
~~~
現在,我需要聲明一個state class 。我把它聲明為一個抽象類(abstract class),并提供一個抽象函數(abstract method)。用以返回type code :
~~~
abstract class EmployeeType {
abstract int getTypeCode();
}
~~~
現在,我可以開始創造subclass 了:
~~~
class Engineer extends EmployeeType {
int getTypeCode () {
return Employee.ENGINEER;
}
}
class Manager extends EmployeeType {
int getTypeCode () {
return Employee.MANAGER;
}
}
class Salesman extends EmployeeType {
int getTypeCode () {
return Employee.SALESMAN;
}
}
~~~
現在進行一次編譯。前面所做的修改實在太平淡了,即使對我來說也太簡單。現在,我要修改type code 訪問函數(accessors),實實在在地把這些subclasses 和Employee class 聯系起來:
~~~
Employee (int type) {
setType (type);
}
int getType() {
return _type;
}
void setType(int arg) {
_type = arg;
}
int payAmount() {
switch (getType()) {
case ENGINEER:
return _monthlySalary;
case SALESMAN:
return _monthlySalary + _commission;
case MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
~~~
這意味我將在這里擁有一個switch 語句。完成重構之后,這將是代碼中惟一的switch 語句,并且只在對象型別發生改變時才會被執行。我也可以運用Replace Constructor with Factory Method 針對不同的case 子句建立相應的factory method 。我還可以立刻再使用Replace Conditional with Polymorphism,從而將其他的case 子句完全消除。
最后,我喜歡將所有關于type code 和subclass 的知識都移到新的class ,并以此結束Replace Type Code with State/Strategy 首先我把type code 的定義拷貝到EmployeeType class 去,在其中建立一個factory method 以生成適當的 EmployeeType 對象,并調整Employee class 中為type code 賦值的函數:
~~~
class Employee...
void setType(int arg) {
_type = EmployeeType.newType(arg);
}
class EmployeeType...
static EmployeeType newType(int code) {
switch (code) {
case ENGINEER:
return new Engineer();
case SALESMAN:
return new Salesman();
case MANAGER:
return new Manager();
default:
throw new IllegalArgumentException("Incorrect Employee Code");
}
}
static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
~~~
然后,我刪掉Employee 中的type code 定義,代之以一個「指向(代表、指涉)Employee 對象」的reference:
~~~
class Employee...
int payAmount() {
switch (getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
~~~
現在,萬事俱備,我可以運用Replace Conditional with Polymorphism 來處理payAmount 函數了。
- 譯序 by 侯捷
- 譯序 by 熊節
- 序言
- 前言
- 章節一 重構,第一個案例
- 起點
- 重構的第一步
- 分解并重組statement()
- 運用多態(Polymorphism)取代與價格相關的條件邏輯
- 結語
- 章節二 重構原則
- 何謂重構
- 為何重構
- 「重構」助你找到臭蟲(bugs)
- 何時重構
- 怎么對經理說?
- 重構的難題
- 重構與設計
- 重構與性能(Performance)
- 重構起源何處?
- 章節三 代碼的壞味道
- Duplicated Code(重復的代碼)
- Long Method(過長函數)
- Large Class(過大類)
- Long Parameter List(過長參數列)
- Divergent Change(發散式變化)
- Shotgun Surgery(散彈式修改)
- Feature Envy(依戀情結)
- Data Clumps(數據泥團)
- Primitive Obsession(基本型別偏執)
- Switch Statements(switch驚悚現身)
- Parallel Inheritance Hierarchies(平行繼承體系)
- Lazy Class(冗贅類)
- Speculative Generality(夸夸其談未來性)
- Temporary Field(令人迷惑的暫時值域)
- Message Chains(過度耦合的消息鏈)
- Middle Man(中間轉手人)
- Inappropriate Intimacy(狎昵關系)
- Alternative Classes with Different Interfaces(異曲同工的類)
- Incomplete Library Class(不完美的程序庫類)
- Data Class(純稚的數據類)
- Refused Bequest(被拒絕的遺贈)
- Comments(過多的注釋)
- 章節四 構筑測試體系
- 自我測試代碼的價值
- JUnit測試框架
- 添加更多測試
- 章節五 重構名錄
- 重構的記錄格式
- 尋找引用點
- 這些重構準則有多成熟
- 章節六 重新組織你的函數
- Extract Method(提煉函數)
- Inline Method(將函數內聯化)
- Inline Temp(將臨時變量內聯化)
- Replace Temp with Query(以查詢取代臨時變量)
- Introduce Explaining Variable(引入解釋性變量)
- Split Temporary Variable(剖解臨時變量)
- Remove Assignments to Parameters(移除對參數的賦值動作)
- Replace Method with Method Object(以函數對象取代函數)
- Substitute Algorithm(替換你的算法)
- 章節七 在對象之間搬移特性
- Move Method(搬移函數)
- Move Field(搬移值域)
- Extract Class(提煉類)
- Inline Class(將類內聯化)
- Hide Delegate(隱藏「委托關系」)
- Remove Middle Man(移除中間人)
- Introduce Foreign Method(引入外加函數)
- Introduce Local Extension(引入本地擴展)
- 章節八 重新組織數據
- Self Encapsulate Field(自封裝值域)
- Replace Data Value with Object(以對象取代數據值)
- Change Value to Reference(將實值對象改為引用對象)
- Replace Array with Object(以對象取代數組)
- Replace Array with Object(以對象取代數組)
- Duplicate Observed Data(復制「被監視數據」)
- Change Unidirectional Association to Bidirectional(將單向關聯改為雙向)
- Change Bidirectional Association to Unidirectional(將雙向關聯改為單向)
- Replace Magic Number with Symbolic Constant(以符號常量/字面常量取代魔法數)
- Encapsulate Field(封裝值域)
- Encapsulate Collection(封裝群集)
- Replace Record with Data Class(以數據類取代記錄)
- Replace Type Code with Class(以類取代型別碼)
- Replace Type Code with Subclasses(以子類取代型別碼)
- Replace Type Code with State/Strategy(以State/strategy 取代型別碼)
- Replace Subclass with Fields(以值域取代子類)
- 章節九 簡化條件表達式
- Decompose Conditional(分解條件式)
- Consolidate Conditional Expression(合并條件式)
- Consolidate Duplicate Conditional Fragments(合并重復的條件片段)
- Remove Control Flag(移除控制標記)
- Replace Nested Conditional with Guard Clauses(以衛語句取代嵌套條件式)
- Replace Conditional with Polymorphism(以多態取代條件式)
- Introduce Null Object(引入Null 對象)
- Introduce Assertion(引入斷言)
- 章節十一 處理概括關系
- Pull Up Field(值域上移)
- Pull Up Method(函數上移)
- Pull Up Constructor Body(構造函數本體上移)
- Push Down Method(函數下移)
- Push Down Field(值域下移)
- Extract Subclass(提煉子類)
- Extract Superclass(提煉超類)
- Extract Interface(提煉接口)
- Collapse Hierarchy(折疊繼承關系)
- Form Template Method(塑造模板函數)
- Replace Inheritance with Delegation(以委托取代繼承)
- Replace Delegation with Inheritance(以繼承取代委托)
- 章節十二 大型重構
- 這場游戲的本質
- Tease Apart Inheritance(梳理并分解繼承體系)
- Convert Procedural Design to Objects(將過程化設計轉化為對象設計)
- Separate Domain from Presentation(將領域和表述/顯示分離)
- Extract Hierarchy(提煉繼承體系)
- 章節十三 重構,復用與現實
- 現實的檢驗
- 為什么開發者不愿意重構他們的程序?
- 現實的檢驗(再論)
- 重構的資源和參考資料
- 從重構聯想到軟件復用和技術傳播
- 結語
- 參考文獻
- 章節十四 重構工具
- 使用工具進行重構
- 重構工具的技術標準(Technical Criteria )
- 重構工具的實用標準(Practical Criteria )
- 小結
- 章節十五 集成
- 參考書目