代码改变世界

设计模式之builder模式

2011-02-12 18:01  hanwesley  阅读(208)  评论(0编辑  收藏  举报
package org.springframework.samples.jpetstore.designpatten;

//真正需要得到的产品
class Product {
	private String info;
	private String desc;

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public String getDesc() {
		return desc;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	public String getInfo() {
		return info;
	}

	public String toString() {
		return info + "," + desc;
	}
}

//构建产品每一个细粒度小部件 
abstract class Builder {
	public abstract void builderFirst();

	public abstract void builderSecond();

	protected Product getResult() {
		return null;
	};
}

class ConcreateBuilder extends Builder {
	private Product p = new Product();

	public void builderFirst() {
		System.out.println("builderFirst");
		p.setInfo("Product Info is Builder");
	}

	public void builderSecond() {
		System.out.println("builderSecond");
		p.setDesc("Product Desc is Builder");
	}

	public Product getResult() {
		return p;
	}
}

//完整组装一个产品
class Director {
	private Builder builder;

	public Director(Builder builder) {
		this.builder = builder;
	}

	public void construct() {
		builder.builderFirst();
		builder.builderSecond();
	}
}

public class BuilderMain {
	public static void main(String[] args) {
		Builder builder = new ConcreateBuilder();
		Director director = new Director(builder);
		director.construct();
		Product product = builder.getResult();
		System.out.println(product);
	}
}