这就是问题所在。我有一个抽象基类Editor
。我也有两个子类GraphEditor
和一个TreeMapEditor
. 的实现TreeMapEditor
基本上包装了 aGraphEditor
并且现在基本上将所有请求转发到底层GraphEditor
.
class TreeMapEditor extends Editor{
private final Editor wrappedEditor = createWrappedEditor();
private createWrappedEditor(){
return new GraphEditor();
}
public void doA(){ //This is the abstract class defined in Editor.
wrappedEditor.doA();
}
public void doB(){ //This is the abstract class defined in Editor.
wrappedEditor.doB();
}
public Editor getWrappeEditor(){
return this.wrappedEditor ;
}
}
GraphEditor
现在我的想法是在没有真正子类化的情况下重用代码GraphEditor
(因此是组合)。GraphEditor
但客户端代码不仅仅是写给执行的Editor
。我如何在这里重构这段代码?我希望所有属于的呼叫Editor
都经过TreeMapEditor
,只有更具体的呼叫经过GraphEditor
.
客户端代码现在如下所示:
public clientCode(Editor editor){
GraphEditor graphEditor = (GraphEditor)editor;
graphEditor .doA(); //This method belongs to Editor()
graphEditor .doB(); //This method belongs to Editor()
graphEditor .doC(); //This method belongs to GraphEditor() only and not to TreeMapEditor
graphEditor .doD();//This method belongs to GraphEditor() only and not to TreeMapEditor
}
}