How to mark a method obligatory?

后端 未结 6 519
囚心锁ツ
囚心锁ツ 2020-12-30 10:21

Suppose you create a class names Person using the builder pattern, and suppose the Builder class contains methods body(), head(), arms()

6条回答
  •  有刺的猬
    2020-12-30 11:02

    Why not calling body(), head(), arms() in the build()-Method if it is really mandatory and returning Person in the build() method?

    [edit]

    Short example:

    public class Builder {
    
    private final String bodyProp;
    
    private final String headProp;
    
    private final String armsProp;
    
    private String hearProps;
    
    public Builder(String bodyProp, String headProp, String armsProp) {
        super();
        this.bodyProp = bodyProp; // check preconditions here (eg not null)
        this.headProp = headProp;
        this.armsProp = armsProp;
    }
    
    public void addOptionalHair(String hearProps) {
        this.hearProps = hearProps;
    }
    
    public Person build() {
        Person person = new Person();
    
        person.setBody(buildBody());
        // ...
    
        return person;
    }
    
    
    
    private Body buildBody() {
        // do something with bodyProp
        return new Body();
    }
    
    
    public static class Person {
    
        public void setBody(Body buildBody) {
            // ...
        }
    }
    
    public static class Body {
    }
    }
    

提交回复
热议问题