定義:講一個複雜對象的構建與它的表示分離,使同樣的構建構建過程可以創建不同的表達形式
使用場景:
(1)相同的方法不同的執行順序,產生不同的事件結果時
(2)多個部件或零件,都可以裝配到到一個對象中,但是產生的結果有不想同時
(3)產品非常的複雜,或者展品類中的調用順序不同產生不同的作用,這個時候使用建造者只非常合適的
(4) 當初始化一個對象特別複雜。如參數特別多,且很多參數具有默認值的時候
我們都知道在android裏面AlertDialog使用的就是建造者模式,雖然很少使用這個類了 但是我們可以嘗試的仿造一下 並且我們做好養成一個好習慣 最寫程序之間 畫出自己的Uml 在根據Uml去實現整個代碼。
我們根據AlerDialog的結構仿出自定義dialog的uml圖
下面我們要做的就是把這個Uml轉換成一個我們用建造模式實現的dialog
實現代碼
public class CustomDialog extends Dialog {
//持有Builder
private static DialogBuilder builder;
private static class DialogParams {
private Context context;
//標題
private String title;
}
public static class DialogBuilder {
//持有Product對象
private DialogParams p;
DialogBuilder(Context context) {
p = new DialogParams();
p.context = context;
}
public DialogBuilder title(String text) {
p.title = text;
return builder;
}
void clear() {
p = null;
}
public CustomDialog create() {
return new CustomDialog(p);
}
//按鈕點擊回調
public interface ButtonClickLister {
void onClick(CustomDialog dialog);
}
}
public static DialogBuilder with(Context context) {
if (builder == null) {
builder = new DialogBuilder(context);
}
return builder;
}
private CustomDialog(DialogParams p) {
//設置沒有標題的Dialog風格
super(p.context, R.style.my_dialog);
setContentView(R.layout.dialog_custom);
TextView title = findViewById(R.id.title_textview_canceldialog);
title.setText(p.title);
}
}
調用
CustomDialog.with(this).title("我是個逗逼").create().show();
這是是自己實現的一個一個建造的demo 順便學着畫類圖 嚮往可以給大家帶去更好的思路。