當(dāng)一個類的構(gòu)造方法中參數(shù)過多時, 可以考慮使用Builder模式.
這樣做的好處是:
為設(shè)置每一個參數(shù)提供一個單獨的API, 讓使用者更明白使用這個參數(shù)的意義.
同時, 對這些參數(shù)的設(shè)置是在內(nèi)部類Builder中完成的, 在目標(biāo)類中不提供設(shè)置這些屬性的值的setter API.這樣就保證了目標(biāo)類的對象在創(chuàng)建后, 這些屬性的值不會再發(fā)生改變.
典型的使用代碼
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle(R.string.simple_list_dialog);
builder.setCancelable(true);
AlertDialog dialog=builder.create();
dialog.show();
AlertDialog對象的創(chuàng)建是由它的內(nèi)部類AlertDialog.Builder負(fù)責(zé)完成的.
在AlertDialog對象創(chuàng)建完成后, 它的這些屬性值也就無法修改了, 因為在調(diào)用了dialog.show();后再去修改這些屬性值也沒有任何的意義.