代码之家  ›  专栏  ›  技术社区  ›  TheLovelySausage

C#带必填字段的步骤生成器

  •  0
  • TheLovelySausage  · 技术社区  · 2 年前

    我目前在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();
    
    0 回复  |  直到 2 年前
        1
  •  1
  •   Fildor    2 年前

    如果要在生成器模式中强制执行特定选项的设置,可以采用不同的方式:

    (列表可能不完整!)

    1. 可以将其作为生成器创建函数的参数。

    举个例子:

    public BuilderIfc Start(string type) { /*implementation here*/ }
    
    1. 您可以通过返回特定接口来强制执行“流”。
    //     vv Next in flow _must be_ ".WithType(string)"
    public IWithType Start() { /*implementation here*/ }
    
    推荐文章