Search code examples
androiddesign-patternsbuilder

how to use Builder Pattern?


I'm creating a view entend FrameLayout now that has about 10 parameters.

I was thinking about using the Builder pattern, similar to how the AlertDialog works. However, I'm not exactly sure what would be the best way to implement this, or if it is even a good idea.

Here is an example of what I was thinking, but with many more variables.

there is problem in this.

I want to use the variable adDetailModel and dataLoader in the init that builder get it.

public class DialogContentList extends FrameLayout {

public static DataLoader dataLoader;
static SwipeRefreshRelativeLayout contentList;
public static AdDetailModel adDetailModel;

public DialogContentList(@NonNull Context context) {
    super(context);

    init(context, null, 0);
}

public DialogContentList(@NonNull Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);

    init(context, attrs, 0);
}

public DialogContentList(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    init(context, attrs, defStyleAttr);
}

public static class Builder {

    private AdDetailModel adDetailModel;
    private DataLoader dataLoader;

    public Builder() {

    }


    public Builder setModel(AdDetailModel adDetailModel) {
        this.adDetailModel = adDetailModel;
        return this;
    }

    public Builder setDataloder(DataLoader dataLoader) {
        this.dataLoader = dataLoader;
        return this;
    }


    public DialogContentList build(final Context context) {
        DialogContentList dialogContentList = new DialogContentList(context);

        return dialogContentList;
    }
}

private void init( Context context, AttributeSet attrs, int defStyleAttr) {

    LayoutInflater.from(context).inflate(R.layout.dialog_content_list, this, true);
    contentList = (SwipeRefreshRelativeLayout) findViewById(R.id.ContentList);
  //
  //        contentList.build(new viewWrapper() {
  //            @Override
 //            public BaseWidget getView() {
 //                return new AdSample(context1, adDetailModel);
//            }
//        }, dataLoader);

 }

}

Solution

  • Your implementation of the Builder pattern is basically correct, although I would argue the Context should be passed in to the constructor of your Builder.

    However, personally, I wouldn't add logic (i.e. DataLoader and AdViewModel) into my View layers. Also, none of the variables at the top of your class should be static, certainly SwipeRefreshRelativeLayout, which will lead to a memory leak.

    Where possible, define your Views entirely in XML, and use the Model-View-Presenter pattern to separate your UI from your logic. You will end up with a far more flexible architecture.