标签:设计模式
首先我们看下抽象工厂模式,是生成一个一个独立的对象。
而 建造者模式 其实是【把生成的几个独立的对象组成一个整体。】
如果不考虑扩展性的话,其实可以只看ContreteBuilder类 和 Product类。像数学中的加法,Part1 + Part2 = Product,实现加法的操作是ContreteBuilder类。
来个事例:
class Director {
public void produce(IBuilder Builder){
Builder.buildPart1("part1");
Builder.buildPart2("part2");
}
}
interface IBuilder {
public void buildPart1(String name1);
public void buildPart2(String name2);
public Product getProduct ();
}
class Builder implements IBuilder {
Product product;
public Builder(){
product = new Product();
}
@Override
public void buildPart1(String name1) {
product.part1Name = name1;
}
@Override
public void buildPart2(String name2) {
product.part2Name = name2;
}
@Override
public Product getProduct() {
return product;
}
}
class Product {
String part1Name;
String part2Name;
public Product (){}
public Product(String part1Name, String part2Name) {
this.part1Name = part1Name;
this.part2Name = part2Name;
}
public String getPart1Name() {
return part1Name;
}
public void setPart1Name(String part1Name) {
this.part1Name = part1Name;
}
public String getPart2Name() {
return part2Name;
}
public void setPart2Name(String part2Name) {
this.part2Name = part2Name;
}
@Override
public String toString() {
return "Product : part1Name= " + part1Name +" , part2Name= " + part2Name;
}
}
public class BuilderTest {
public static void main(String[] args) {
Product product = new Product();
IBuilder builder = new Builder();
Director director = new Director();
director.produce(builder);
product = builder.getProduct();
System.out.println(product.toString());
}
}
由指导者 Director 把name 传进去就实现了组装。
这样就实现了建造者模式。
尝试一下吧。
标签:设计模式
原文地址:http://blog.csdn.net/u011845742/article/details/44753669