重叠构造器、Builder模式

   当存在做个参数时,但是有些是必选的,有些事不必选的情况下用重叠构造器、Builer模式比较好

     重叠构造器

   

public student(String name, int age){
  this(name,age,""); 
}
public student(String name, int age,String address){
  this(name,age,address,0); 
}
public student(String name, int age,String address,int telphone){
  this(name,age,address,telephone,""); 
}
public student(String name, int age,String address,int telphone,String nickname){
  this(name,age,address,telephone,nickname); 
}

 这样的话当你创建 new Student("张三",22);这样其它值就为0或“”了。

   

Builder模式

public class BuilderModel {
   private final String name;
   private final int age;
   private final String number;
   private  final String address;
   //private final String nickname;
   private final int tel;
   
   public static class Builder{
	   //必填参数
	   private final String name;
	   private final int age;
	   //可算参数
	   private String number;
	   private String address;
	   private int tel;
	   //name 和age 为必填参数
	   public Builder(String name ,int age){
		   this.name = name;
		   this.age = age;
	   }
	   //可选参数方法池
	   public Builder setNumber(String val){
		    this.number =val; 
		    return  this;
	   }
	   public Builder setAddress(String val){
			this.address = val ;
			return this;		
	   }
	   public Builder setTel(int val){
		    this.tel = val;
		    return this;
	   }
	   public BuilderModel buid(){
		   return new BuilderModel(this);
	   }
	   
   }
   
	private BuilderModel(Builder builder){
		this.name = builder.name;
		this.age = builder.age;
		//this.nickname = b
		this.address = builder.address;
		this.number = builder.number;
		this.tel = builder.tel;
	   
	}

	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        BuilderModel model = new BuilderModel.Builder("zs",22).setAddress("北京朝阳区").setNumber("12345").setTel(110).buid();
	    System.out.println(model.name+model.age);
	    //model.age = 2;  final type should not be asigned again!
	}
}

 

这样 对于每个参数都比较清晰明了,更加易读,有人可能会问为什么不用对象封装属性,因为用对象封装属性当作参数的时候,不能确定它的不变动性(即比如你打算第一个方法调用 Student 对象,下面又有一个方法调Student对象,但是当你在第一个方法里面如果对Student 对象做了修改的话,那样后面一个也就跟着修改了,因为是同一个引用)

例如

public class BuilderModel {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BuilderModel.Student stu = new BuilderModel.Student("张三",22);
		method1(stu);
		method2(stu);		
	}
	public static class Student{		
		public  String name;
		public int age;
        public Student(String name,int age){
		   this.name = name;
		   this.age = age;
 		}
	}
	public static void method1(Student stu){
	   stu.name = "李四";	
	}
	public static void method2(Student stu){
	   System.out.println(stu.name);
	}
	
}

 

对于方法中的参数是对象时,前面加final是不影响修改这个对象里面的方法的。

 

 如有任何缺陷请大家不吝赐教,必当洗耳恭听!

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(builder)