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