设计模式之建造者模式

建造者模式

  1. 建造者模式结构图:

  2. 示例代码:

    public class BuilderTest {
    
        public static void main(String[] args) {
            ConcreteBuilder builder = new ConcreteBuilder();
            Product product =builder.builderPartA("partA")
                					.builderPartB("partB")
                					.builder();
            System.out.println(product);
        }
    
        // 抽象建造者
        public interface Builder{
            Builder builderPartA(String partA);
            Builder builderPartB(String partB);
            Product builder();
        }
    
        // 具体建造者
        public static class ConcreteBuilder implements Builder{
            private Product product = new Product();
            @Override
            public Builder builderPartA(String partA) {
                product.setPartA(partA);
                return this;
            }
    
            @Override
            public Builder builderPartB(String partB) {
                product.setPartB(partB);
                return this;
            }
    
            @Override
            public Product builder() {
                return product;
            }
        }
    
        // 产品
        @Data
        public static class Product {
    
            private String partA;
            private String partB;
    
        }
    
    }
    
  3. 总结:

    优点:封装性好,将构建与表示分离,扩展性好,便于控制细节;

    缺点:需要多创建一个建造者,如果产品内部发生变化,创建者也要修改,后期维护成本较大.

posted @ 2021-04-22 23:52  justKen  阅读(42)  评论(0编辑  收藏  举报