建造者模式(Builder Pattern):將一個復雜對象的構建與它的表示分離橙凳,使得同樣的構建過程可以創(chuàng)建不同的表示茧吊。
實例
以構建Dialog為例豆村,一般Dialog中包含Dialog標題葡兑,Dialog內(nèi)容缨历,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'}