Java采用内部构造器Builder模式进行对类进行构建

好处:

  能保证重叠构造器模式的安全性;

  能保证JAVABeans模式的可读性;

package cn.lonecloud.builder;
/**
 * 使用内部类构建器来对这个类进行构造
 * @Title: MyConstractor.java
 * @Package cn.lonecloud.builder
 * @Description: 
 * @author lonecloud
 * @webSite http://wwww.lonecloud.cn
 * @date 2016年9月12日 上午10:17:11
 */
public class MyConstractor {

	//some field of class
	private final int size;
	
	private final int servings;
	
	private final int fat;
	
	private final int sodium;
	
	private final int age;
	//using getMethod
	public int getSize() {
		return size;
	}
	public int getServings() {
		return servings;
	}
	public int getFat() {
		return fat;
	}
	public int getSodium() {
		return sodium;
	}
	public int getAge() {
		return age;
	}
	
	@Override
	public String toString() {
		return "MyConstractor [size=" + size + ", servings=" + servings
				+ ", fat=" + fat + ", sodium=" + sodium + ", age=" + age + "]";
	}
	//using constractMethod init field
	private MyConstractor(Builder builder){
		this.size=builder.size;
		this.servings=builder.servings;
		this.fat=builder.fat;
		this.sodium=builder.sodium;
		this.age=builder.age;
	}
	//using static class to set this class
	public static class Builder{
		//some field of staticClass
		private final int size;
		
		private final int servings;
		//using method to set field
		private  int fat=0;
		
		private  int sodium=0;
		
		private  int age=0;
		//using constractorMethod to init this final field
		public Builder(int size, int servings) {
			this.size = size;
			this.servings = servings;
		}
		//write method to set field;
		public Builder fat(int fat){
			this.fat=fat;
			return this;
		}
		public Builder sodium(int sodium){
			this.sodium=sodium;
			return this;
		}
		public Builder age(int age){
			this.age=age;
			return this;
		}
		//return MyConstractor
		public MyConstractor build(){
			return new MyConstractor(this);
		}
		
	}
}

测试类:

package cn.lonecloud.constactor;

import org.junit.Test;

import cn.lonecloud.builder.MyConstractor;

public class MyTest {

	@Test
	public void constractorTest(){
		MyConstractor myConstractor = new MyConstractor.Builder(1,2).age(100).build();
		System.out.println(myConstractor.toString());
	}
}

 

posted @ 2016-09-12 10:59  lonecloud  阅读(1077)  评论(0编辑  收藏  举报
我的博客即将同步至 OSCHINA 社区,这是我的 OSCHINA ID:lonecloud,邀请大家一同入驻:https://www.oschina.net/sharing-plan/apply