JavaRush /Java Blog /Random-JA /パターンビルダー
Нина Можарская
レベル 17
Киев

パターンビルダー

Random-JA グループに公開済み
このパターンは、クラスに同じタイプのパラメーターが多数あり、その順序と目的を覚えるのが難しい場合に使用することをお勧めします。
パターンビルダー - 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;     }
このメソッドでは、mainオブジェクトを作成するときに、Builder必要なパラメーターを持つ静的クラスのコンストラクターが呼び出されます。次に、必要なすべてのオプションのパラメーターがドットを通じて呼び出されます。buidl();最後に、オブジェクトを生成する メソッドが呼び出されます。
Good good = new Good.Builder(40, 20)
        .c(2)
        .d(4)
        .e(23)
        .f(9)
        .buidl();
2 つの必須パラメーターと 1 つのオプションのパラメーターを持つオブジェクトを作成する場合は、次のようになります。
Good good = new Good.Builder(40, 20)
        .c(2)
        .buidl();
必須パラメータを 2 つだけ指定してオブジェクトを作成する場合は、次のようになります。
Good good = new Good.Builder(40, 20)
         .buidl();
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION