建造者模式,用的太多太多,简洁方便 不做过多的解释。下面看具体实现代码,易懂。
思路是,在dialog中创建一个静态内部类builder,builder中的属性,都具有默认值,builder中的属性跟dialog中的属性类型数量一致,创建一个参数是builder的dialog构造方法,将builder中的属性复制给dialog。为了符合设计模式,最好有一个builder 或者create方法。
public class AlertDialog {
private String title;
private String content;
private String color;
public String toString() {
return "AlertDialog [title=" + title + ", content=" + content
+ ", color=" + color + "]";
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
private AlertDialog(Builder builder){
this.title=builder.title;
this.content=builder.content;
this.color=builder.color;
}
public static class Builder{
private String title="提示框";
private String content="";
private String color="white";
public Builder title(String title){
this.title=title;
return this;
}
public Builder content(String content){
this.content=content;
return this;
}
public Builder color(String color){
this.color=color;
return this;
}
public AlertDialog build(){
return new AlertDialog(this);
}
}
}
测试调用时
public class test {
/**
* @param args
*/
public static void main(String[] args) {
AlertDialog dialog = new AlertDialog.Builder()
.title("你是煞笔吗")
.color("red")
.content("肯定是")
.build();
System.out.println(dialog.toString());
}
}