Builder vs Factory Design Patttern in specific code

问题描述 投票:-1回答:1

就我而言,我想问的是哪种更好的使用方式,工厂或制造商的设计模式。

长话短说,我有带参数的类Action:transferRate,recoverRate,成本和名称。在我的程序中,我将拥有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设计模式吗? :

Action closeSchool = new Action().withTransferRateBlock(0.5).withRecoverRateBlock(0).withCost(2).withName("Close Schools");
Action[] allActions = {closeSchool};
java design-patterns factory builder
1个回答
2
投票

工厂示例:

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
}

Builder示例:Builder模式更多地是为了避免在创建实例时出现问题。例如,对于缺少的信息。

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。

© www.soinside.com 2019 - 2024. All rights reserved.