我目前在C#应用程序中有一个非常基本的步骤生成器,它允许所有字段都是可选的,并且可以很好地实现这一点(尽管这使得它不是真正的步骤生成器)。
我知道必填字段可以作为参数添加到构造函数中,但我想知道是否有一种方法可以将必填字段作为一个步骤添加,从而通过使用接口而不是构造函数参数来处理必填字段,使其保持作为一个步骤生成器。
我有一门哑巴课来演示
class Animal {
private String type;
private String name;
public Animal(AnimalBuilder builder) {
this.type = builder.type;
this.name = builder.name;
}
public String getType() { return this.type; }
public String getName() { return this.name; }
}
然后步骤生成器(有点)是
class AnimalBuilder {
private Builder builder;
public String type;
public String name;
public BuilderIfc start() {
this.builder = new Builder();
return this.builder;
}
public interface withTypeIfc {
BuilderIfc withType(String type);
}
public interface withNameIfc {
BuilderIfc withName(String name);
}
public interface BuilderIfc {
BuilderIfc withType(String type);
BuilderIfc withName(String name);
Animal build();
}
public class Builder : AnimalBuilder, withTypeIfc, withNameIfc, BuilderIfc {
public BuilderIfc withType(String type) {
this.type = type;
return this;
}
public BuilderIfc withName(String name) {
this.name = name;
return this;
}
public Animal build() {
return new Animal(this);
}
}
}
在这些情况下,它可以正常工作
// allow : animal has type and name
animal = new AnimalBuilder().start().withType("Dog").withName("Spanky").build();
// allow : animal has type
animal = new AnimalBuilder().start().withType("Bear").build();
但它不适用于这种情况,因为
withType
应该是必需的,而不是可选的
// do not allow : animal must have type
animal = new AnimalBuilder().start().build();