建造者模式-仿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());
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值