gpt4 book ai didi

java - 这是实现工厂方法设计模式的正确方法吗

转载 作者:行者123 更新时间:2023-12-01 12:50:46 25 4
gpt4 key购买 nike

我必须根据某些标准对不同的特许经营权实现不同的费用结构。我为 FranchiseFeeStructure 创建一个抽象类

    public abstract class FranchiseFeeStructure {
private BigDecimal registrationFee=1500;
protected BigDecimal monthlyFee;

public BigDecimal getMonthlyFees(){
return monthlyFee;
}

public BigDecimal calculateFee{
//calculate fee here
return fee;
}
}

现在,对于不同的结构,我创建了扩展 FranchiseFeeStructure 的类,例如

public class ST1 extends FranchiseFeeStructure{
@Override
void getMonthlyFee(){
monthlyFee=890;
}

}

还有ST2、ST3等各种结构。我们有一个类有静态工厂方法。

public class GetFeeStructureFactory {

public static FranchiseFeeStructure getFranchiseFeeStructure(String franchiseFeeStructureType){

if(franchiseFeeStructureType == null){
return null;
}
if(franchiseFeeStructureType.equalsIgnoreCase("ST1")) {
return new ST1();
}
else if(franchiseFeeStructureType.equalsIgnoreCase("ST2")){
/// so on...

}
}

现在将其用作

FranchiseFeeStructure franchiseFeeStructure = GetFeeStructureFactory.getFranchiseFeeStructure("ST1");
franchiseFeeStructure.getMonthlyFee();
franchiseFeeStructure.calculateFee();

这是实现方法工厂模式的正确方法吗?如果我错了或者有任何改进的建议,请告诉我。

最佳答案

在工厂实现中问题并非如此。这是抽象类的实现方式。它通过调用(名称错误的)方法 getMonthlyFee() 强制每个调用者初始化月费。调用者不必这样做。你的抽象类应该依赖......抽象方法来做到这一点:

public abstract class FranchiseFeeStructure {
private static final BigDecimal REGISTRATION_FEE = new BigDecimal(1500);

public final BigDecimal calculateFee {
BigDecimal monthlyFee = getMonthlyFee();
// TODO compute
return fee;
}

/**
* Subclasses must implement this method to tell what their monthly fee is
*/
protected abstract BigDecimal getMonthlyFee();
}

public class ST1 extends FranchiseFeeStructure {
@Override
protected BigDecimal getMonthlyFee(){
return new BigDecimal(890);
}
}

这样,调用者就不需要初始化月费。它需要做的就是

BigDecimal fee = FeeStructureFactory.getFranchiseFeeStructure("ST1").calculateFee();

请注意,如果月费始终是一个恒定值,您甚至不需要一个抽象类和多个子类。您所需要的只是一个将月费作为构造函数参数的类。

关于java - 这是实现工厂方法设计模式的正确方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24228649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com