[英]How to implement the Template design pattern?
I have this exercise that I need to refactor using Template design pattern. 我需要使用模板设计模式来重构此练习。 I have seen a basic explanation of how it works, but I can't get a clear idea of how I should implement my solution. 我已经看到了有关其工作原理的基本解释,但是我不清楚如何实现解决方案。 Could anyone help me out? 有人可以帮我吗? What would be the logic in this case? 在这种情况下,逻辑是什么?
I have this BodyFatCalculator class: 我有这个BodyFatCalculator类:
package bodyfat;
public class BodyFatCalculator {
private double height;
private double waist;
private double weight;
private double hip;
private double abdomen;
public BodyMeasures( double height, double waist, double weight, double hip, double abdomen ) {
this.height = height;
this.waist = waist;
this.weight = weight;
this.hip = hip;
this.abdomen = abdomen;
}
/**
* @return the height
*/
public double getHeight() {
return height;
}
/**
* @return the waist
*/
public double getWaist() {
return waist;
}
/**
* @return the weight
*/
public double getWeight() {
return weight;
}
/**
* @return the hip
*/
public double getHip() {
return hip;
}
/**
* @return the abdomen
*/
public double getAbdomen() {
return abdomen;
}
}
So, it looks like the way to calculate for men and women is the same except for women use getHip()
and men use getAbdomen()
. 因此,除了女性使用getHip()
和男性使用getAbdomen()
之外,男性和女性的计算方式似乎相同。 This could be refactored to have a base class BodyFatCalculator
define the template for doing this calculation, that calls a "template method" to get the specific implementation of which measurement to use (so, you would add a FemaleBodyFatCalculator
and MaleBodyFatCalculator
, and they would each override an abstract method like getMiddle(BodyMeassures body)
. Female would return body.getHip()
and male would return body.getAbdomen()
. 可以将其重构为让基类BodyFatCalculator
定义用于执行此计算的模板 ,该类调用“模板方法”以获取要使用的度量的具体实现(因此,您将添加FemaleBodyFatCalculator
和MaleBodyFatCalculator
,它们将各自覆盖诸如getMiddle(BodyMeassures body)
类的抽象方法,女性将返回body.getHip()
而男性将返回body.getAbdomen()
。
So, the gist of it is that your base class has a multi-step algorithm to implement, so it implements the general framework or template, which calls overridable or abstract methods that are implemented by the subclasses. 因此,其要点在于,您的基类具有要实现的多步算法,因此它实现了通用框架或模板,该框架或模板调用了由子类实现的可重写或抽象方法。
It seems like a trivial thing to refactor in this case, but such is homework, I guess ;) 在这种情况下,重构似乎是一件微不足道的事情,但是我想这就是作业;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.