在那篇文章中我也提到,基本代码中的客户端需要知道的东西太多了,因此这次实现的时候我使用反射来实现。
先给出类结构图:
代码如下:
package builderpattern;
/**
* 抽象的建造者类
* @author the5fire
*
*/
public abstract class AbstractBuilder {
public abstract void buidPart1();
public abstract void buildPart2();
public abstract Product getProduct();
}
package builderpattern;
/**
* 具体的产品1的建造者
* @author the5fire
*
*/
public class Product1Builder extends AbstractBuilder {
private Product1 product = new Product1();
@Override
public void buidPart1() {
product.add("Builder1_add_part1");
}
@Override
public void buildPart2() {
product.add("Builder1_add_part2");
}
@Override
public Product getProduct() {
return product;
}
}
package builderpattern;
/**
* 具体的产品2的建造者
* @author the5fire
*
*/
public class Product2Builder extends AbstractBuilder {
private Product2 product = new Product2();
@Override
public void buidPart1() {
product.add("Builder2_add_part1");
}
@Override
public void buildPart2() {
product.add("Builder2_add_part2");
}
@Override
public Product getProduct() {
return product;
}
}
package builderpattern;
/**
* 具体产品1
* @author the5fire
*
*/
public class Product1 extends Product{
private static StringBuffer strPart = new StringBuffer("product1:");
public String say() {
return strPart.toString();
}
@Override
public void add(String str) {
strPart.append(str);
}
}
package builderpattern;
/**
* 具体产品2
* @author the5fire
*
*/
public class Product2 extends Product {
private static StringBuffer strPart = new StringBuffer("product2:");
public String say() {
return strPart.toString();
}
@Override
public void add(String str) {
strPart.append(str);
}
}
package builderpattern;
/**
* 指挥者类,指挥完成产品构建,供客户端调用
* @author the5fie
*
*/
public class Director {
private AbstractBuilder builder = null;
private Product product = null;
public Director(){}
/**
* 通过构造函数确定要建造那个产品
* @param productName
*/
public Director(String productName) {
try {
builder = (AbstractBuilder)Class.forName("builderpattern." + productName + "Builder").newInstance();
product = (Product) Class.forName("builderpattern." + productName).newInstance();
System.out.println(builder.getClass().toString());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 实现构建
*/
public void contruct() {
builder.buidPart1();
builder.buildPart2();
}
public Product getProduct() {
return product;
}
}
package builderpattern;
public class Client {
public static void main(String[] args) {
Director director = new Director("Product1");
director.contruct();
System.out.println(director.getProduct().say());
director = new Director("Product2");
director.contruct();
System.out.println(director.getProduct().say());
}
}
不知道你发现没有,其实这些模式大多是往类上面或者两个类之间再加上一个类,也就是加上一层,来增加灵活性。那么在这个模式中我能不能够将Director也变为抽象的呢?即在其上加一个类以增加其灵活性。
- from the5fire.com
----EOF-----
微信公众号:Python程序员杂谈
微信公众号:Python程序员杂谈