英文:
enforcing common initilisation steps to an abstract method
问题
我目前正在重构一组类,可以简化如下:
public abstract class A {
public abstract Output doStuff(Input in);
}
public class B extends A {
public Output doStuff(Input in) {
// 做一些操作并返回输出
}
}
现在,我想在A
类中添加一个字段,其值是从Input in
派生的,最好不改变子类中的任何内容(大约有20个类像B
这样)。
基本上,我想找到一种在每次从doStuff()
调用时调用那个init
方法(见下文)的方法,而无需在A
类中实现该方法,也不更改扩展A
的类中的内容。
你知道是否有任何优雅的方法来实现这一点吗?
public abstract class A {
private Object property;
public abstract Output doStuff(Input in);
private void init(Input in){
property = in.getProperty();
}
}
public class B extends A {
public Output doStuff(Input in) {
// 做一些操作并返回输出
}
}
英文:
I'm currently refactoring a set of class that could be simplified as follows:
public abstract class A {
public abstract Output doStuff(Input in);
}
public class B extends A {
public Output doStuff(Input in) {
// dostuff and return an output
}
}
Now, I'd like to add a field in A
whose value is derived from Input in
, preferably without changing anything in the subclasses (there are around 20 classes like B
)
Basically I'd like to find a way to call that init
method (see bellow) at every call from doStuff()
, without having to implement the method in class A
, nor changing things in class extending A.
Do you know any elegant ways to do this ?
public abstract class A {
private Object property;
public abstract Output doStuff(Input in);
private init(Input in){
property=in.getProperty();
}
}
public class B extends A {
public Output doStuff(Input in) {
// dostuff and return an output
}
}
答案1
得分: 1
你可以在 A
类中简单地编写一个方法,该方法调用了 init()
方法和 doStuff()
方法。这样,init()
方法会自动地为每个子类调用。
public abstract class A {
private Object property;
public Output doStuffWithInit(Input in) {
this.init(in);
return this.doStuff(in);
}
public abstract Output doStuff(Input in);
private void init(Input in){
property = in.getProperty();
}
}
使用方的类需要被修改,以调用 doStuffWithInit()
方法,从而确保每次都调用了 init()
方法。
英文:
You can simply write a method in A
which calls the init()
method and the doStuff()
method. That way the init()
method gets called for every sub class automatically.
public abstract class A {
private Object property;
public Output doStuffWithInit(Input in) {
this.init(in);
return this.doStuff(in);
}
public abstract Output doStuff(Input in);
private init(Input in){
property=in.getProperty();
}
}
The consuming classes has to be changed to call doStuffWithInit()
instead to make sure that init()
is called everytime.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论