建造者模式(Builder Pattern):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
实例
以构建Dialog为例,一般Dialog中包含Dialog标题,Dialog内容,Dialog确认按钮,Dialog取消按钮。
Dialog类
public class Dialog {
private String title;
private String content;
private String button1;
private String button2;
public void setTitle(String title){
this.title = title;
}
public void setContent(String content) {
this.content = content;
}
public void setNegativeButton(String button) {
this.button1 = button;
}
public void setPositiveButton(String button) {
this.button2 = button;
}
@Override
public String toString() {
return "Dialog{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
", button1='" + button1 + '\'' +
", button2='" + button2 + '\'' +
'}';
}
}
DialogBuilder为一个抽象的构建器
public abstract class AbstractDialogBuilder {
protected Dialog dialog;
public Dialog getDialog() {
return dialog;
}
public void createDialog(){
dialog = new Dialog();
}
public abstract void setTitle(String title);
public abstract void setContent(String content);
public abstract void setNegativeButton(String button);
public abstract void setPositiveButton(String button);
}
public class DialogBuilder extends AbstractDialogBuilder {
@Override
public void setTitle(String title) {
dialog.setTitle(title);
}
@Override
public void setContent(String content) {
dialog.setContent(content);
}
@Override
public void setNegativeButton(String button) {
dialog.setNegativeButton(button);
}
@Override
public void setPositiveButton(String button) {
dialog.setPositiveButton(button);
}
}
测试
public class Test {
public static void main(String[] args) {
DialogBuilder builder = new AlertDialogDialogBuilder();
builder.createDialog();
builder.setTitle("title");
builder.setContent("content");
builder.setNegativeButton("negativeButton");
builder.setPositiveButton("positiveButton");
Dialog dialog = builder.getDialog();
System.out.println(dialog.toString());;
}
}
输出
Dialog{title='title', content='content', button1='negativeButton', button2='positiveButton'}