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);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章