我想问一下,在我的情况下,工厂或构建器的设计模式更适合使用什么。
长话短说,我有一个类Action的参数:transferRate,recoverRate,cost和name。
在我的程序中,我将有一个包含30个(始终相同(Action对象的数组。每个都有相同的参数设置。
我正在考虑更多地使用工厂,但如果你给我哪个更好的建议,我将不胜感激。
简称:
import lombok.Getter;
工厂:
@Getter
abstract public class Action {
protected double transferRateBlock;
protected double recoverRateBlock;
protected int cost;
protected String name;
}
public class CloseAirports extends Action {
public CloseAirports(){
this.transferRateBlock = -0.4;
this.recoverRateBlock = 0;
this.cost = 3;
this.name = "Close airports";
}
}
public class CloseBorders extends Action {
public CloseBorders(){
this.transferRateBlock = -0.5;
this.recoverRateBlock = 0;
this.cost = 4;
this.name = "Close Borders";
}
}
我有30个子类。每个子类都将转到另一个类中的数组。客户端只是在使用这些操作,从未创建任何操作。每件事都是事先准备好的。
CloseAirports closeAirports = new CloseAirports();
CloseBorders closeBorders = new CloseBorders();
Action[] allActions = {closeAirports, closeBorders};
或者我应该在这个实现中使用Builder Design Pattern?:
Action closeSchool = new Action().withTransferRateBlock(0.5).withRecoverRateBlock(0).withCost(2).withName("Close Schools");
Action[] allActions = {closeSchool};
工厂示例:
public class ActionFactory implements AbstractFactory<Action>{
@Override
public Action createAction(int type) {
switch(type) {
case 1: return new CloseShops();
case 2: return new CloseAirports();
default: return null;
}
}
因此,如果您想区分不同的类型,并避免由开发人员自己构建对象,这就是要使用的方法。他仍然可以向createAction方法传递额外的参数。
List<Action> myActions = new ArrayList<>();
ActionFactory fact = new ActionFactory();
for ( int i = 0; i < 10; i++ ) {
int type = assumeThisReadIntMethodExists();
myActions.add(fact.createAction(type)); // this will add CloseShops or CloseAirports depending on the type passed
}
生成器示例:生成器模式更多的是为了避免在创建实例时出现问题。例如,针对缺少的信息。
public class CloseShops {
private final String nameOfShop;
private CloseShops(String name) {
this.nameOfShop = name; // as you can see, no check for null
// it's always better to check for null before starting a constructor
}
public String getNameOfShop() {
return nameOfShop;
}
// additional methods
public static class Builder {
private String name;
public Builder withName(String name) {
this.name = name;
return this;
}
public Builder fromCloseShops(CloseShops original) {
this.name = original.getNameOfShop();
return this;
}
public CloseShops build() {
assertNotNull("The name is mandatory", name);
// this assert to avoid calling the constructor if the name is null
return new CloseShops(this.name);
}
}
这可以这样称呼:
Action b = new CloseShops.Builder().withName("shopName").build();
因此,如果要减少代码,请选择Factory。