建造者模式可以将一个产品的内部表象(产品的零件)与产品的生成过程分割开来,从而可以使一个建造过程生成具有不同的内部表象的产品对象。
产品类:
package com.javapatterns.builder;
public class Product
{
public Product()
{
// System.out.println("product is initing.");
}
}
抽象建造方法:
abstract public class Builder
{
public abstract void buildPart1();
public abstract void buildPart2();
public abstract Product retrieveResult();
}
具体的建造类:产品的零件制造
public class ConcreteBuilder extends Builder
{
/**
* @label Creates
*/
private Product product = new Product() ;
public void buildPart1()
{
System.out.println("build part one.");
}
public void buildPart2()
{
System.out.println("build part two.");
}
public Product retrieveResult()
{
return product;
}
}
产品的建造过程:
public class Director
{
/**
* @link aggregation
* @directed
* @clientRole builder*/
private Builder builder;
public Director(Builder builder)
{
this.builder = builder;
}
public void construct()
{
builder = new ConcreteBuilder();
builder.buildPart1();
builder.buildPart2();
builder.retrieveResult();
//continue with other code
}
}
测试
public class Client
{
/**
* @link aggregation
* @directed
*/
private static Director director;
private static Builder builder = new ConcreteBuilder();
public void requestBuild()
{
// director = new Director(builder);
}
public static void main(String[] args)
{
director = new Director(builder);
director.construct();
}
}