强制执行通用的初始化步骤到一个抽象方法。

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月23日 16:43:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/64496783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定