lundi 29 mars 2021

Fluent builder design pattern - how to force customer to set variables

I have a problem with design pattern. Let's say i have a simple class:

public class Person {

    private String name;
    private String surname;
    private int age;

    private Person(){}

    public String toString()
    {
        return "name: "+name+" surname: "+surname+" age: "+age;
    }

    public static final class Builder{

        private String name;
        private String surname;
        private int age;

        public Builder name (String name){
            this.name = name;
            return this;
        }

        public Builder surname (String surname){
            this.surname = surname;
            return this;
        }

        public Builder age (int age){
            this.age = age;
            return this;
        }

        public Person build(){
            Person person = new Person();
            person.name=name;
            person.surname=surname;
            person.age=age;
            return person;
        }
    }
}

It works fine, but it's not required to set variables before invoking "build" method. How could i change that?

Aucun commentaire:

Enregistrer un commentaire