JavaRush /Java 博客 /Random-ZH /模式生成器
Нина Можарская
第 17 级
Киев

模式生成器

已在 Random-ZH 群组中发布
当类具有大量相同类型的参数并且很难记住它们的顺序和用途时,建议使用此模式。
模式生成器 - 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();
如果我想创建一个具有两个必需参数和一个可选参数的对象,它将如下所示:
Good good = new Good.Builder(40, 20)
        .c(2)
        .buidl();
如果我想创建一个只有两个必需参数的对象,它看起来像这样:
Good good = new Good.Builder(40, 20)
         .buidl();
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION