`
to_zoe_yang
  • 浏览: 138947 次
  • 性别: Icon_minigender_2
  • 来自: 01
社区版块
存档分类
最新评论

Effective java 第二条

 
阅读更多

遇到多个构造器参数时要考虑用构建器。

 

package Builder;

public class Student {

	private final String name;
	private final int id;
	private final String sex;
	private final String birth;
	private final String home;
	
	public static class Builder{
		private String name;
		private int id;
		private String sex;
		private String birth;
		private String home;
		
		public Builder setName(String name){
			this.name = name;
			return this;
		}

		public Builder setId(int id) {
			this.id = id;
			return this;
		}

		public Builder setSex(String sex) {
			this.sex = sex;
			return this;
		}

		public Builder setBirth(String birth) {
			this.birth = birth;
			return this;
		}

		public Builder setHome(String home) {
			this.home = home;
			return this;
		}
		
		public Student builder(){
			return new Student(this);
		}
	}
	
	private Student(Builder builder){
		this.name = builder.name;
		this.sex = builder.sex;
		this.id = builder.id;
		this.birth = builder.birth;
		this.home = builder.home;
	}
	
	
	
	public String toString(){
		return this.name + "'s sex is " + this.sex + "," + this.id + "," + this.home;
	}
	public static void main(String[] args){
		Student s = new Student.Builder().setName("zoe").setSex("Female").setId(1016).setHome("No").builder();
		System.out.println(s);
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics