JavaRush /Java Blog /Random EN /Pattern (Template) Builder

Pattern (Template) Builder

Published in the Random EN group
This pattern is recommended when a class has a large number of parameters of the same type and it is difficult to remember their order and purpose.
Pattern (Template) Builder - 1
public class Good{
   public final int a;
   public final int b;
   public final int c;
   public final int d;
   public final int e;
   public final int f;
//Реализация Builder через статический внутренний класс
public static class Builder{
//Обязательные параметры
    public int a;
    public int b;
//Необязательные параметры со значениями по умолчанию
public int c = 0;
public int d = 0;
public int e = 0;
public int f = 0;
//Конструктор с обязательными параметрами
public Builder(int a, int b){
this.a=a;
this.b=b;
}
//Методы с возвращающим типом Builder для необязательного параметра с, d, e, f,
  public Builder c (int val) {
            c = val;
            return this;
        }
  public Builder d (int val) {
            d = val;
            return this;
        }
  public Builder e (int val) {
            e = val;
            return this;
        }
  public Builder f (int val) {
            f = val;
            return this;
        }
//Метод с возвращающим типом Good для генерации an object
public Good buidl() {
            return new Good (this); }
private Good(Builder builder) {
        a = builder.a;
        b = builder.b;
        c = builder.c;
        d = builder.d;
        e = builder.e;
        f = builder.f;     }
Now in the method, mainwhen creating an object, the static class constructor Builderwith the required parameters is called. Then all the necessary optional parameters are called through the dot. Finally, a method is called buidl();to generate the object.
Good good = new Good.Builder(40, 20)
        .c(2)
        .d(4)
        .e(23)
        .f(9)
        .buidl();
If I want to create an object with two required and one optional parameters, it would look like this:
Good good = new Good.Builder(40, 20)
        .c(2)
        .buidl();
If I want to create an object with only two required parameters, it looks like this:
Good good = new Good.Builder(40, 20)
         .buidl();
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION