阅读 88

Builder设计模式

日常写法Demo

    public class Student {
    	private String name;
    	private String nickName;
    	private String sex;
    	private int age;
    	private int weight;
    	private int height;

    	public Student(String name, String nickName, String sex, int age, int weight, int height) {
    		// TODO Auto-generated constructor stub
    		this.name = name;
    		this.nickName = nickName;
    		this.sex = sex;
    		this.age = age;
    		this.weight = weight;
    		this.height = height;
    	}

    	@Override
    	public String toString() {
    		// TODO Auto-generated method stub
    		return "student info:name=" + name + "\n" +
    							"nickname=" + nickName + "\n" +
    							"sex=" + sex + "\n" + 
    							"age=" + age + "\n" + 
    							"weight=" + weight + "\n" +
    							"height=" + height;
    	}

    	public static class Builder {
    		private String name;
    		private String nickName;
    		private String sex;
    		private int age;
    		private int weight;
    		private int height;

    		public Builder name(String name) {
    			this.name = name;
    			return this;
    		}
    		public Builder nickName(String nickName) {
    			this.nickName = nickName;
    			return this;
    		}
    		public Builder sex(String sex) {
    			this.sex = sex;
    			return this;
    		}
    		public Builder age(int age) {
    			this.age = age;
    			return this;
    		}
    		public Builder weight(int weight) {
    			this.weight = weight;
    			return this;
    		}
    		public Builder height(int height) {
    			this.height = height;
    			return this;
    		}
    		public Student build() {
    			return new Student(name, nickName, sex, age, weight, height);
    		}
    	} 
    }
复制代码
复制代码

以下是测试程序:

    public class Client {
    	public static void main(String [] args) {
    		Student student = new Student.Builder().name("rock")
    		.nickName("store")
    		.sex("boy")
    		.age(12)
    		.weight(60)
    		.height(176).build();
    		System.out.println(student);
    	}
    }
复制代码

程序运行结果如下:

student info:name=rock
nickname=store
sex=boy
age=12
weight=60
height=176
复制代码

Android中Builder使用场景

在开发过程中,经常使用的builder模式其实就是上文所说的日常写法,Android中最常见的builder模式就是AlertDialog的创建过程了,以下是AlertDialog创建过程的常见写法。

    AlertDialog.Builder builder = new AlertDialog.Builder(context)
                        .setTitle(title)
                        .setView(view)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                              @Override
                              public void onClick(DialogInterface dialog, int which) {

                              }
                         })
                         .setNegativeButton(android.R.string.cancel, null);
    builder.create().show();
复制代码

感觉很熟悉,这就是我们最常用的AlertDialog的构建过程。扒一扒源码,由于AlertDialog.Builder的源码较多,就不全部贴出来,感兴趣的同学可以自行看一下。

    public static class Builder {
        private final AlertController.AlertParams P;

        public Builder(Context context) {
            this(context, resolveDialogTheme(context, ResourceId.ID_NULL));
        }

       ......

        public Builder setTitle(@StringRes int titleId) {
            P.mTitle = P.mContext.getText(titleId);
            return this;
        }

        public Builder setTitle(CharSequence title) {
            P.mTitle = title;
            return this;
        }

        public Builder setCustomTitle(View customTitleView) {
            P.mCustomTitleView = customTitleView;
            return this;
        }

        ......

        public Builder setMessage(CharSequence message) {
            P.mMessage = message;
            return this;
        }

       public Builder setPositiveButton(@StringRes int textId, final OnClickListener listener) {
            P.mPositiveButtonText = P.mContext.getText(textId);
            P.mPositiveButtonListener = listener;
            return this;
        }
        ......

        public AlertDialog create() {
            // Context has already been wrapped with the appropriate theme.
            final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);
            P.apply(dialog.mAlert);
            dialog.setCancelable(P.mCancelable);
            if (P.mCancelable) {
                dialog.setCanceledOnTouchOutside(true);
            }
            dialog.setOnCancelListener(P.mOnCancelListener);
            dialog.setOnDismissListener(P.mOnDismissListener);
            if (P.mOnKeyListener != null) {
                dialog.setOnKeyListener(P.mOnKeyListener);
            }
            return dialog;
        }

    }
复制代码

总结

Builder模式的目标是将复杂对象的创建过程进行分解,使对象的构建与表示分离,使得同样的构建过程可以创建不同的表示。在实际开发过程中,通常是在复杂对象内部申明静态内部类Builder,在Builder中保存复杂对象的属性,然后使用create或者build函数将保存的属性设置给对象。

文章分类
Android
文章标签