1. 程式人生 > >建造者模式-仿android-AlertDialog的實現

建造者模式-仿android-AlertDialog的實現

建造者模式,用的太多太多,簡潔方便 不做過多的解釋。下面看具體實現程式碼,易懂。

思路是,在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());
	}

}