Effective Java第2条:遇到多个构造器参数时要考虑用构建器(Builder)

注:以下内容摘自《Effective Java》

package hunnu.edu.item2;
/**
 * Effective Java第2条:遇到多个构造器参数时要考虑用构建器(Builder)
 * 优点:保证了线程安全和构造方便。
 * @author Administrator
 *
 */
public class BuilderPattern {
	private final int a;
	private final int b;
	private final int c;
	private final int d;
	private final int e;
	private final int f;
	
	public static class Builder{
		//必须的参数
		private final int a;
		private final int b;
		
		//可选参数-初始化一个默认值
		private int c = 0;
		private int d = 0;
		private int e = 0;
		private int f = 0;
		
		public Builder(int a,int b){
			this.a = a;
			this.b = b;
		}
		public Builder c(int v){
			c = v;
			return this;
		}
		public Builder d(int v){
			d = v;
			return this;
		}
		public Builder e(int v){
			e = v;
			return this;
		}
		public Builder f(int v){
			f = v;
			return this;
		}
		
		public BuilderPattern build(){
			return new BuilderPattern(this);
		}
	}
	
	private BuilderPattern(Builder builder){
		a = builder.a;
		b = builder.b;
		c = builder.c;
		d = builder.d;
		e = builder.e;
		f = builder.f;
	}
	
	public String toString(){
		return "a="+a+" b="+b+" c="+c+" d="+d+" e="+e+" f="+f;
	}
	
	//测试入口
	public static void main(String args[]){
		BuilderPattern bp = (new BuilderPattern.Builder(240, 8)).c(3).d(4).e(5).f(10).build();
		System.out.println("结果:"+bp);
		BuilderPattern bp1 = (new BuilderPattern.Builder(24, 80)).c(3).d(4).e(5).f(10).build();
		System.out.println("结果:"+bp1);
		
	}
}

 Google buffer多采用这种构造方式。

你可能感兴趣的:(java,C++,c,C#,F#)