设计模式之建造者模式

定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

结构图如下:

设计模式之建造者模式_第1张图片

示例代码:

public class Product {

	List<String> parts = new ArrayList<String>();
	
	public void add(String part) {
		parts.add(part);
	}
	
	public void show() {
		System.out.println("产品创建...");
		for (String part : parts) {
			System.out.println(part);
		}
	}
}
public interface Builder {

	public void buildPartA();

	public void buildPartB();

	public Product gerResult();
}
public class ConcreteBuilder1 implements Builder {

	private Product product = new Product();
	@Override
	public void buildPartA() {
		// TODO Auto-generated method stub
		product.add("部件X");
	}

	@Override
	public void buildPartB() {
		// TODO Auto-generated method stub
		product.add("部件Y");
	}

	@Override
	public Product gerResult() {
		// TODO Auto-generated method stub
		return product;
	}
}
public class ConcreteBuilder2 implements Builder {

	private Product product = new Product();
		@Override
	public void buildPartA() {
		// TODO Auto-generated method stub
		product.add("部件A");
	}

	@Override
	public void buildPartB() {
		// TODO Auto-generated method stub
		product.add("部分B");
	}

	@Override
	public Product gerResult() {
		// TODO Auto-generated method stub
		return product;
	}

}
public class Director {

	public void construct(Builder builder) {
		builder.buildPartA();
		builder.buildPartB();
	}
}
客户端代码如下所示:

public class Client {

	public static void main(String[] args) {
		
		Director director = new Director();
		
		Builder builder1 = new ConcreteBuilder1();
		
		Builder builder2 = new ConcreteBuilder2();
		
		builder1.buildPartA();
		builder1.buildPartB();
		
		director.construct(builder1);
		builder1.gerResult().show();
		
		director.construct(builder2);
		builder2.gerResult().show();
	}
}

运行结果如下:

产品创建...
部件X
部件Y
部件X
部件Y
产品创建...
部件A
部分B



你可能感兴趣的:(设计模式之建造者模式)