Java设计模式 建造模式(Builder)

直接上代码
public class Contact {
	final String name;
	final String email;
	final String phone;
	
	private Contact(final Builder builder){
		this.name = builder.name;
		this.email = builder.email;
		this.phone = builder.phone;
	}
	
	public String toString(){
		String str = "name = "+this.name+", email = "+this.email+", phone = "+this.phone;
		System.out.println(str);
		return str;
	}
	
	public static class Builder{
	
		private String name;
		private String email;
		private String phone;
		public Builder(){
			
		}
		
		public Builder setName(String name){
			this.name = name;
			return this;
		}
		public Builder setEmail(String email){
			this.email = email;
			return this;
		}
		
		public Builder setPhone(String phone){
			this.phone = phone;
			return this;
		}
		
		public Contact build(){
			if(this.name == null){
				this.name = "Andy";
			}
			if(this.email == null){
				this.email = "xxxxxxx@163.com";
			}
			if(this.phone == null){
				this.phone = "xxxxxxxxxxx";
			}
			
			return new Contact(this);
		}
	}
	
}

测试调用

		Contact contact = new Contact.Builder().build();
		contact.toString();
		
		Contact contact1 = new Contact.Builder().setName("andy").setEmail("andy@163.com").setPhone("11111111111").build();
		contact1.toString();


测试输出

name = Andy, email = xxxxxxx@163.com, phone = xxxxxxxxxxx
name = andy, email = andy@163.com, phone = 11111111111


**如有错误请博友指出!**


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值