[英]Refactor object to use decorator pattern
使用第三方 API,我為它們的對象編寫了包裝類。 明顯/標准的方式是這樣的:
public class WrapperFoo implements MyWrapper {
private Foo f;
public WrapperFoo(Foo f) {
this.foo = foo;
}
public int getMyParam() {
return f.getParam();
}
public void setMyParam(int param) {
if(param < 0) throw new IllegalArgumentException("Param must not be negative!");
f.setParam(param);
}
}
但是, Foo
的get
方法很昂貴。 所以相反,我這樣做:
public class WrapperFoo implements MyWrapper {
private Foo f;
private int myParam;
public WrapperFoo(Foo f) {
this.foo = foo;
}
public int getMyParam() {
return param;
}
public void setMyParam(int param) {
if(param < 0) throw new IllegalArgumentException("Param must not be negative!");
this.param = param;
f.setParam(param);
}
}
但是,出於測試原因,我希望能夠在不需要第三方 API 實例的情況下擁有所有功能。 所以我想重構現有的包裝器版本,其中第三方 API 功能只是一個裝飾器:
public class WrapperImpl implements MyWrapper {
private int myParam;
public int getMyParam() {
return myParam;
}
public void setMyParam(int param) {
if(param < 0) throw new IllegalArgumentException("Param must not be negative!");
this.myParam = param;
}
}
public class WrapperFoo implements MyWrapper {
private MyWrapper backing;
private Foo f;
public WrapperFoo(MyWrapper backing, Foo f) {
this.backing = backing;
this.foo = f;
}
public int getMyParam() {
return backing.getMyParam();
}
public void setMyParam(int param) {
backing.setMyParam(int param);
f.setParam(param);
}
}
顯然,我真正的課程要復雜得多; 我怕很容易犯錯。 我想這就是測試的目的,但是......問題:
對於真正的裝飾器/適配器,適配器應該具有相同的接口,因此您的包裝方法get/setMyParam()
應該是get/setParam()
並且如果可能,您應該實現第 3 方接口(如果存在)。
代碼應該無法從 API 的角度區分您的包裝器和原始包裝器之間的區別。
現在回答你的問題:
主要問題:在 Fowler's Refactoring 中,每次重構都有一個分步過程以確保正確性。 這個過程有嗎?
是的,Joshua Kerievsky 的Refactoring to Patterns稱之為“提取適配器”,並且有一個循序漸進的例子。 我在網上找不到確切的代碼示例,但之前/之后的 UML 在 這里
這種重構有名字嗎? “提取裝飾器”?
如前所述,它被稱為提取適配器
這樣做是否有意義(與從頭開始制作測試類相比)
也許取決於您的用例。
有沒有可以做到這一點的IDE? 我目前正在使用 Eclipse 4.3.1
您可以使用 Eclipse 的重構工具來執行每個步驟,但我會猶豫是否嘗試進行復雜的重構,就像您暗示只需按一下按鈕一樣,即使存在可以讓您使用的工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.