我可以使用构建器模式创建抽象片段类吗?

时间:2015-12-10 12:03:26

标签: android android-fragments builder-pattern

我使一些片段扩展到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创建继承片段类的实例?

1 个答案:

答案 0 :(得分:2)

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

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()方法来调用该构造函数。 E.g

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

现在Fragment不能拥有带参数的私有构造函数或构造函数,因此不能真正使用Builder模式。