建造者模式
将一个复杂的对象的构建与他的表示分离,使得同样的构建过程可以创建不同的表示
Product类
package com.hml.builder; import java.util.ArrayList; import java.util.List; public class Product { private List<String> parts = new ArrayList<String>(); public void addPart(String part) { parts.add(part); } public void show() { } }
Builder
package com.hml.builder; public interface Builder { public void buildPathA(); public void buildPathB(); public Product getResult(); }
ConcreateBuilderA
package com.hml.builder; public class ConcreateBuilderA implements Builder { private Product p = new Product(); public void buildPathA() { p.addPart("A"); } public void buildPathB() { p.addPart("B"); } public Product getResult() { return p; } }
ConcreateBuilderB
package com.hml.builder; public class ConcreateBuilderB implements Builder { private Product p = new Product(); public void buildPathA() { p.addPart("A"); } public void buildPathB() { p.addPart("B"); } public Product getResult() { return p; } }
Director
package com.hml.builder; public class Director { public Director(Builder builder) { builder.buildPathA(); builder.buildPathB(); } }
类图
构建者模式主要是用于创建一些比较复杂的对象,这些对象内部构建间的建造顺序通常是稳定的,但对象内部的构建通常面临着复杂的变化。