菜鸟硕枫设计模式系列之6 建造者模式

建造者模式是设计模式中另一个重要的创建对象的方法模式。它的特点主要是稳定了创建的过程,比如下面的例子中就是每个产品的创建过程都包括创建A部分和创建B部分,但不同的builder可以有自己的方式去创建产品,比如不同的房地产商可以建不同的房子【大房子、小房子】,只要建造过程稳定一致就可以了。

建造者模式类图:
                菜鸟硕枫设计模式系列之6 建造者模式


建造者接口:
package builderPattern;

public interface Builder {
	
	Product getProduct();
	Object buildProductPartA();
	Object buildProductPartB();
	
}


具体建造者:


public class ConcreteBuilder1 implements Builder{

	public Object buildProductPartA() {
		
		System.out.println("build Big ProductPartA with tools .");
		Object object = new Object();
		return object;
	}

	public Object buildProductPartB() {
		
		System.out.println("build Big ProductPartB with tools .");
		Object object = new Object();
		return object;
	}

	public Product getProduct() {
		// TODO Auto-generated method stub
		return new Product(buildProductPartA(),buildProductPartB());
	}

	
}


package builderPattern;

public class ConcreteBuilder2 implements Builder{

	public Object buildProductPartA() {
		
		System.out.println("build Small ProductPartA with tools .");
		Object object = new Object();
		return object;
	}


	public Object buildProductPartB() {
		
		System.out.println("build Small ProductPartB with tools .");
		Object object = new Object();
		return object;
	}


	public Product getProduct() {
		// TODO Auto-generated method stub
		return new Product(buildProductPartA(),buildProductPartB());
	}

	
}


具体产品:
package builderPattern;

public class Product {

	private Object partA;
	private Object partB;
	
	public Product(Object partA,Object partB){
		this.partA = partA;
		this.partB = partB;
	}
}


指挥者:
package builderPattern;

public class Director {

	private Builder builder;
	
	public Director(Builder builder){
		this.builder = builder;
	}
	
	public Product getProduct(){
		return builder.getProduct();
	}
}


测试类:
package builderPattern;

public class BuilderTest {

	public static void main(String[] args){
		
		Builder builder = new ConcreteBuilder1();
		Director director = new Director(builder);
		
		director.getProduct();
		
		System.out.println("建造另外一件产品");
		
		director = new Director(builder);
		Builder builder2 = new ConcreteBuilder2();
		
		director.getProduct();
	}
}


说明:说明:产品这块当然也可以通过抽象出一个抽象类或接口了,只要这一类产品创建过程一样,都可以通过建造者模式去创建。

你可能感兴趣的:(java,设计模式)