建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
UML图:
Builder:
package com.cnblog.clarck;
/**
* 抽象建造者,确定产品有两个部分A和B组成,并声明一个得到产品组合后得到结果的方法getResult.
*
* @author clarck
*
*/
public abstract class Builder {
public abstract void buildPartA();
public abstract void buildPartB();
public abstract Product getResult();
}
Director:
package com.cnblog.clarck;
/**
* 指挥者
*
* @author clarck
*
*/
public class Director {
public void Construct(Builder builder) {
builder.buildPartA();
builder.buildPartB();
}
}
Product:
package com.cnblog.clarck;
import java.util.ArrayList;
import java.util.List;
/**
* 产品类,由多个部分组成
*
* @author clarck
*
*/
public class Product {
private 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);
}
}
}
ConcrateBuilder1:
package com.cnblog.clarck;
/**
* 具体建造者
*
* @author clarck
*
*/
public class ConcrateBuilder1 extends Builder {
private Product product = new Product();
@Override
public void buildPartA() {
product.add("部件A");
}
@Override
public void buildPartB() {
product.add("部件B");
}
@Override
public Product getResult() {
return product;
}
}
ConcrateBuilder2:
package com.cnblog.clarck;
public class ConcrateBuilder2 extends Builder {
private Product product = new Product();
@Override
public void buildPartA() {
product.add("部件X");
}
@Override
public void buildPartB() {
product.add("部件Y");
}
@Override
public Product getResult() {
return product;
}
}
Client:
package com.cnblog.clarck;
/**
* 测试类
*
* @author clarck
*
*/
public class Client {
public static void main(String[] args) {
Director director = new Director();
Builder builder1 = new ConcrateBuilder1();
Builder builder2 = new ConcrateBuilder2();
director.Construct(builder1);
Product product1 = builder1.getResult();
product1.show();
director.Construct(builder2);
Product product2 = builder2.getResult();
product2.show();
}
}