Search code examples
androidandroid-fragmentsbuilder-pattern

Can I make abstract fragment class with builder pattern?


I makes some fragments extends topFragment class. But it has variable arguments - custom listeners, some models, etc.

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;
        }
    }
}

here is second fragment class

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(); It works. then how to make instance of inheritance fragment class with builder?


Solution

  • The implementation of the outer environment of the class bounded to the Builder, has a private Constructor which takes a Builder object as argument, E.g.

    public class ThirdFragment extend TopFragment {
        @Override
        protected void doSomething() {
            // do something.
        }
    
       private ThirdFragment(Builder builder) {
          // use the members of builder to build your object
       } 
    }
    

    and the Builder itself has a build() method which invokes that constructor. E.g

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

    now Fragment can't have either private constructor or constructor that takes parameters, so you can't really use the Builder pattern.