每天一整理-java设计模式之builder模式

来源:互联网 发布:华为mate10抢购软件 编辑:程序博客网 时间:2024/05/23 13:03
Builder模式在个人理解上是,封装了过程,就是一个复杂的对象,允许在用户只知道构造细节的情况下进行构造出来,一下是自己在做一个Android项目时候,利用builder模式写的一个功能,当然,这个小案例只是演示用,因为并没有把这种类抽象出来,个人认为并不是一个很合格的案例。
public class TopLayout extends RelativeLayout {    public TopLayout(Context context)    {        this(context, null);    }    public TopLayout(Context context, AttributeSet attrs) {        this(context, attrs, 0);        // TODO Auto-generated constructor stub    }    public TopLayout(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    public void setLefView(View view,LayoutParams params){        if(view!=null){        params.addRule(RelativeLayout.CENTER_VERTICAL,RelativeLayout.TRUE);        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT,RelativeLayout.TRUE);        params.setMargins(20,0,0,0);        view.setLayoutParams(params);        this.addView(view);}    }    public void setMiddleView(View view,LayoutParams params){        if(view!=null){        params.addRule(RelativeLayout.CENTER_IN_PARENT,RelativeLayout.TRUE);        view.setLayoutParams(params);        this.addView(view);}    }    public void setRightView(View view,LayoutParams params){        if(view!=null){        params.addRule(RelativeLayout.CENTER_VERTICAL,RelativeLayout.TRUE);        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);        view.setLayoutParams(params);        view.setPadding(0,0,20,0);        this.addView(view);}    }}
//builder的编写
package builder;import android.content.Context;import android.graphics.Color;import android.view.View;import android.view.ViewGroup;import android.widget.RelativeLayout;import definedview.TopLayout;/** * Created by Administrator on 2017/1/14. */public class TopLayoutBuilder {    TopLayout topLayout;    public TopLayoutBuilder(Context context){        topLayout =new TopLayout(context);    }    public  TopLayoutBuilder setLeftView(View view,RelativeLayout.LayoutParams params){       topLayout.setLefView(view,params);        return  this;    }    public TopLayoutBuilder setMiddleView(View view,RelativeLayout.LayoutParams params){        topLayout.setMiddleView(view,params);        return  this;    }    public TopLayoutBuilder setRightView(View view ,RelativeLayout.LayoutParams params){        topLayout.setRightView(view,params);        return  this;    }    public TopLayoutBuilder setBackgroundColor(int color){        topLayout.setBackgroundColor(color);        return  this;    }    public TopLayout create(){        ViewGroup.LayoutParams params =new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,150);        topLayout.setLayoutParams(params);        return  topLayout;    }}
这边就是通过builder来构建TopLayout builder封装了toplayout的创建过程
在Android的应用中 alertDialog就是通过builder模式来书写的,有兴趣的可以去看看源码
还是那句老话,菜鸟一个如果有错还望指出,欢迎评论,批评我

                                             
0 0