1

我让一些片段扩展了 topFragment 类。但它有可变参数 - 自定义侦听器、一些模型等。

public abstract class TopFragment extend Fragment {
    public interface OnCustomListener {
        void onCustomListener();
    }
    protected OnCustomListener onCustomListener;
    protected int importantValue;
    protected String importantString;

    protected abstract void doSomething();

    public static class Builder() {
        protected OnCustomListener onCustomListener;
        protected int importantValue;
        protected String importantString;

        public Builder(OnCustomListener onCustomListener) {
            this.onCustomListener = onCustomListener;
        }

        public Builder setValue(int value) {
            this.importantValue = value;
            return this;
        }

        public Builder setString(String value) {
            this.importantString = value;
            return this;
        }
    }
}

这是第二个片段类

public class SecondFragment extend TopFragment {
    @Override
    protected void doSomething() {
        // do something.
    }
}

public class ThirdFragment extend TopFragment {
    @Override
    protected void doSomething() {
        // do something.
    }
}

TopFragment fragment = new SecondFragment(); 有用。那么如何用builder创建继承片段类的实例呢?

4

1 回答 1

2

绑定到 的类的外部环境的实现有一个以对象为参数Builder的私有,例如ConstructorBuilder

public class ThirdFragment extend TopFragment {
    @Override
    protected void doSomething() {
        // do something.
    }

   private ThirdFragment(Builder builder) {
      // use the members of builder to build your object
   } 
}

并且它Builder本身有一个build()调用该构造函数的方法。例如

    public ThirdFragment build() {
        return new ThirdFragment(this);
    }

现在Fragment不能有私有构造函数或带参数的构造函数,所以你不能真正使用该Builder模式。

于 2015-12-10T12:16:33.023 回答