设计模式(Design Pattern) - 创建型模式(Creational Pattern) - 建造者模式(Builder)
将一个复杂的构建算法和表示分离,导致同样的构建过程可以建造不同的表示。
1、说明:
(1)Product 产品;
(2)Builder 建造者.接口;
(3)BuilderA 建造者.实现类;
(4)Director 导演类。
2、Java实现,代码如下:
(1)Product
package com.java.designPattern.builder;
/**
* 产品
*
*/
public class Product {
private String part1;
private String part2;
public String getPart1() {
return part1;
}
public void setPart1(String part1) {
this.part1 = part1;
}
public String getPart2() {
return part2;
}
public void setPart2(String part2) {
this.part2 = part2;
}
}
(2)Builder
package com.java.designPattern.builder;
/**
* 建造者(接口)
*
*/
public interface Builder {
public void buildPart1();
public void buildPart2();
public Product getProduct();
}
(3)BuilderA
package com.java.designPattern.builder;
/**
* 建造者.实现类
*
*/
public class BuilderA implements Builder {
private Product product = new Product();
@Override
public void buildPart1() {
product.setPart1("part1");
}
@Override
public void buildPart2() {
product.setPart2("part2");
}
@Override
public Product getProduct() {
return product;
}
}
(4)Director
package com.java.designPattern.builder;
/**
* 导演类
*
*/
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void construct() {
builder.buildPart1();
builder.buildPart2();
}
}
(5)Test
package com.java.designPattern.builder;
/**
* 测试类
*
*/
public class Test {
public static void main(String[] args) {
Builder builder = new BuilderA();
Director director = new Director(builder);
director.construct();
Product product = builder.getProduct();
System.out.println(product.getPart1());
System.out.println(product.getPart2());
}
}
输出:
part1
part2