建造者模式:是对象的创建模式。建造模式可以将一个产品的内部表象与产品的生产过程分割开来,从而可以使一个建造过程生成具有不同的内部表象的产品对象。
建造模式可以有三种角色:产品、建造器、把建造器组装成产品的对象(导演者)
下面上代码:
产品类:
package build; /** * 产品 */ 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; } }
建造器接口:
package build; /** * 建造器 */ public interface Builder { void buildPart1(); void builPart2(); Product retrieveResult(); }
具体实现建造器接口实现类:
package build; public class ConcreteBuilder implements Builder { private Product product = new Product(); @Override public void buildPart1() { product.setPart1("构建第一部分"); } @Override public void builPart2() { product.setPart2("构建第二部分"); } @Override public Product retrieveResult() { return product; } }
导演类:
package build; /** * 组装建造器的导演者 */ public class Director { /** * 持有当前需要使用的建造器对象 */ private Builder builder; public Director(Builder builder) { this.builder = builder; } public void construct(){ builder.buildPart1(); builder.builPart2(); } }
Client类:
package build; public class Client { public static void main(String[] args) { Builder builder = new ConcreteBuilder(); Director director = new Director(builder); director.construct(); Product product = builder.retrieveResult(); System.out.println(product.getPart1()); System.out.println(product.getPart2()); } }