morristech
1/3/2019 - 2:49 PM

Pattern builder

Pattern builder

public class User {
  private final String firstName;  //requis
  private final String lastName;  //requis
  private final String adress;  //facultatif
  private final String phone;   //facultatif
  private final int age;  //facultatif

  private User (UserBuilder builder){ //Le constructeur DOIT être private ce qui empeche la creation d'objet par new (pas abstract?)
    this.firstName = builder.firstName;
    this.lastName = builder.lastName;
    this.adress = builder.adress;
    this.phone = builder.phone;
    this.age = builder.age;
  }
  
  public String getFirstname() {
  return firstName;
  }
  
   public String getLastname() {
  return lastName;
  }
  
   public String getAdress() {
  return adress;
  }
  
   public String getPhone() {
  return phone;
  }
  
   public int getAge() {
  return age;
  }
  
  public static class UserBuilder{
    
     //Seul les attributs obligatoires doivent être en final
  private final String firstName;  //requis
  private final String lastName;  //requis
  private String adress;  //facultatif
  private String phone;   //facultatif
  private int age;  //facultatif
  
    //Le constructeur du builder ne prend en paramètre que les attributs obligatoires
    public UserBuilder (String firstName, String lastName){
      this.firstName = firstName;
      this.lastName = lastName;
  }
    
    public UserBuilder age (int age){
      this.age = age;
      return this;
    }
    public UserBuilder adress (String adress){
      this.adress = adress;
      return this;
    }
    public UserBuilder phone (String phone){
      this.phone = phone;
      return this;
    }
    
    //method build pour creer User (avec le nombre d'attribut, minimum 2 et max 5
    public User build() {
      return new User(this);
      //nested Builder class is necessary
     
    }
   
}
  
  
  ////////////////
  
  // Pour creer l'objet
  
  User student = new User.Builder ("Georges", "Duroy").
                 age(99).
                 address("Paris").
                 build()