[英]How can I fix the client code so that I get code reuse via composition?
Here's the problem. 这是问题所在。 I have one abstract base class
Editor
. 我有一个抽象基类
Editor
。 I also have two subclasses GraphEditor
and a TreeMapEditor
. 我也有两个子类
GraphEditor
和TreeMapEditor
。 The implementation of TreeMapEditor
basically wraps a GraphEditor
and for now basically forwards all requests to the underlying GraphEditor
. TreeMapEditor
的实现基本上包装了GraphEditor
,现在基本上将所有请求转发到基础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 ;
}
}
Now my idea is to reuse the code for GraphEditor
without really subclassing GraphEditor
(Hence the composition) . 现在,我的想法是重用
GraphEditor
的代码,而无需真正地GraphEditor
(因此是组成部分)。 But the client code is written to the implementation of GraphEditor
and not merely Editor
. 但是客户端代码被写入
GraphEditor
的实现中,而不仅仅是Editor
。 How can I refactor this code here? 如何在此处重构此代码? I want all the calls belonging to
Editor
to go through the TreeMapEditor
and only more specific calls to go through the GraphEditor
. 我希望所有属于
Editor
的调用都通过TreeMapEditor
而只有更具体的调用才通过GraphEditor
。
The client code looks like this now: 客户端代码现在看起来像这样:
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
}
} }
You might want to look for a concept between GraphEditor and your other two; 您可能想要在GraphEditor和您的另外两个之间寻找一个概念。 is there a construct within what you're doing that could be represented by a class that extends GraphEditor but is not a full-functioned GraphEditor or TreeMapEditor?
您正在执行的操作中是否有一个结构可以由扩展GraphEditor的类表示,而不是功能齐全的GraphEditor或TreeMapEditor? IF there is, common code might go in it.
如果存在,则可能会包含通用代码。
But I would be careful to keep to implementing a representation of something in your problem space, rather than just putting methods into classes in an inheritance hierarchy because that's where you need them. 但是我会小心地继续在问题空间中实现某种表示,而不是仅仅将方法放入继承层次结构中的类中,因为这是您需要它们的地方。 That bottom-up style of creating classes can lead to poor design, hard to understand until someone says "Oh, he just wanted this method available here.".
这种自下而上的创建类的样式会导致糟糕的设计,直到有人说“哦,他只是想在这里使用此方法”之前,否则很难理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.