美文网首页
设计模式-建造者模式

设计模式-建造者模式

作者: 蜗牛写java | 来源:发表于2019-12-13 18:57 被阅读0次

    设计模式-建造者模式

    概念

    将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示

    用户只需指定需要建造的类型就可以得到他们,建造过程及细节不需要知道

    类型:创建型

    使用场景

    • 如果一个对象有非常复杂的内部结构(很多属性)
    • 把对象创建和使用分离

    优点

    • 封装性好,创建和使用分离

    • 扩展性好,建造类之间独立,一定程度上解耦

    • 便于控制细节风险

      建造者是独立的,因此可以对建造过程逐步细化,不影响其他模块

    缺点

    • 产生多余的Builder对象
    • 产品内部发生变化,建造者需要修改

    UML

    建造者模式UML.png
    • Product 产品类

      public class Product {
          public void doSomething() {
              //...
          }
      }
      
    • Builder抽象建造者

      public abstract class Builder {
          //设置产品的不同部分,以获得不同的产品
          public abstract void setPart();
          //构建产品
          pubilc abstract Product buildProduct();
      }
      
    • ConcreteBuilder具体建造者

      public class ConcreteProduct extends Builder {
          private Product product = new Product();
          //设置产品零件
          pubilc void setPart() {
              //设置Product相关属性等
          }
          //组件一个产品
          public Product buildProduct() {
              return product;
          }
      }
      
    • Director导演类

      导演类起到了封装作用,避免了高层模块深入到建造者内部的实现。如果建造者模式比较庞大,导演类可以有多个

      public class Director {
          private Builder builder = new ConcreteProduct();
          //构建不同的产品
          public Product getAProduct() {
              //设置不同的零件,可以产生不同的产品
              builder.setPart();
              return builder.buildProduct();
          }
      }
      

    实例

    我们以组装电脑为例:组装电脑需要主板、CPU、内存、硬盘等等

    UML

    实例UML.png

    产品类

    public class Computer {
    
        //各个组件 与 电脑 是整体与部分关系;该场景主要是建造者模式;组件就不在抽象,均以Object为类型
        private Object cpu;
        private Object mainBoard;
        private Object memory;
        private Object disk;
        private Object power;
    
        public Object getCpu() {
            return cpu;
        }
        public void setCpu(Object cpu) {
            this.cpu = cpu;
        }
    
        public Object getMainBoard() {
            return mainBoard;
        }
        public void setMainBoard(Object mainBoard) {
            this.mainBoard = mainBoard;
        }
    
        public Object getMemory() {
            return memory;
        }
        public void setMemory(Object memory) {
            this.memory = memory;
        }
    
        public Object getDisk() {
            return disk;
        }
        public void setDisk(Object disk) {
            this.disk = disk;
        }
    
        public Object getPower() {
            return power;
        }
        public void setPower(Object power) {
            this.power = power;
        }
    
        @Override
        public String toString() {
            return "{" +
                    "cpu:" + cpu + ",  " +
                    "mainBoard:" + mainBoard + ",  " +
                    "memory:" + memory + ",  " +
                    "disk:" + disk + ",  " +
                    "power:" + power +
                    "}";
        }
    }
    

    抽象建造者

    public interface IComputerBuilder {
    
        void buildCpu(Object cpu);
    
        void buildMainBoard(Object mainBoard);
    
        void buildMemory(Object memory);
    
        void buildDisk(Object disk);
    
        void buildPower(Object power);
    
        Computer getComputer();
    }
    

    具体构建者

    public class ComputerBuilderImpl implements IComputerBuilder {
    
        private Computer computer = new Computer();
    
        @Override
        public void buildCpu(Object cpu) {
            computer.setCpu(cpu);
        }
    
        @Override
        public void buildMainBoard(Object mainBoard) {
            computer.setMainBoard(mainBoard);
        }
    
        @Override
        public void buildMemory(Object memory) {
            computer.setMemory(memory);
        }
    
        @Override
        public void buildDisk(Object disk) {
            computer.setDisk(disk);
        }
    
        @Override
        public void buildPower(Object power) {
            computer.setPower(power);
        }
    
        @Override
        public Computer getComputer() {
            return computer;
        }
    }
    

    导演类

    public class Director {
    
        public void construct(IComputerBuilder builder) {
            builder.buildCpu("i5");
            builder.buildDisk("500G");
            builder.buildMainBoard("hp-MainBoard");
            builder.buildMemory("16G");
            builder.buildPower("hp-Power");
        }
    }
    

    使用场景

    public class Client {
        // 一个消费者向电脑门店购买电脑;电脑商家组件电脑后,卖给消费者
        public static void main(String[] args) {
            IComputerBuilder builder = new ComputerBuilderImpl();
            Director director = new Director();
            director.construct(builder);
    
            Computer computer = builder.getComputer();
    
            System.out.println(computer);
        }
    }
    

    源码案例

    1. StringBuilder (源码做了提取)

      abstract class AbstractStringBuilder implements Appendable, CharSequence {
          char[] value;
          int count;
          
          public AbstractStringBuilder append(String str) {
              if (str == null)
                  return appendNull();
              int len = str.length();
              ensureCapacityInternal(count + len);
              //将 value 插入到 str 对应的char数组中;从0开始插入
              str.getChars(0, len, value, count);
              
              count += len;
              //返回自己
              return this;
          }
      }
      
    public final class StringBuilder extends AbstractStringBuilder 
    implements java.io.Serializable, CharSequence {
    
     //组织产品零件
     @Override
        public StringBuilder append(Object obj) {
            return append(String.valueOf(obj));
        }
    
        //组织产品零件
        @Override
        public StringBuilder append(String str) {
            super.append(str);
            return this;
        }
        
        //构建出产品
        @Override
        public String toString() {
            // Create a copy, don't share the array
            return new String(value, 0, count);
        }
    
    }
    
    1. ES-BulkProcessor (静态内部类方式)

      public class BulkProcessor implements Closeable {
          //...无关代码
          //构造器,该构造器 不是 public,由静态内部类构建
          BulkProcessor(Client client, 
                        BackoffPolicy backoffPolicy, 
                        Listener listener, 
                        @Nullable String name, 
                        int concurrentRequests, 
                        int bulkActions, ByteSizeValue bulkSize, 
                        @Nullable TimeValue flushInterval) {
              //属性设置
              this.... = ...
          }
          
          //静态内部类构建 对象
          public static class Builder {
              private final Client client;
              private final Listener listener;
      
              private String name;
              private int concurrentRequests = 1;
              private int bulkActions = 1000;
              private ByteSizeValue bulkSize = new ByteSizeValue(5, ByteSizeUnit.MB);
              private TimeValue flushInterval = null;
              private BackoffPolicy backoffPolicy = BackoffPolicy.exponentialBackoff();
      
              public Builder(Client client, Listener listener) {
                  this.client = client;
                  this.listener = listener;
              }
              
              public Builder setName(String name) {
                  this.name = name;
                  return this;
              }
              
              public Builder setConcurrentRequests(int concurrentRequests) {
                  this.concurrentRequests = concurrentRequests;
                  return this;
              }
              
              public Builder setBulkActions(int bulkActions) {
                  this.bulkActions = bulkActions;
                  return this;
              }
      
              public Builder setBulkSize(ByteSizeValue bulkSize) {
                  this.bulkSize = bulkSize;
                  return this;
              }
      
              public Builder setFlushInterval(TimeValue flushInterval) {
                  this.flushInterval = flushInterval;
                  return this;
              }
      
              public Builder setBackoffPolicy(BackoffPolicy backoffPolicy) {
                  this.backoffPolicy = backoffPolicy;
                  return this;
              }
      
              public BulkProcessor build() {
                  return new BulkProcessor(client, backoffPolicy, listener, name, concurrentRequests, bulkActions, bulkSize, flushInterval);
              }
          }
      }
      

    相关文章

      网友评论

          本文标题:设计模式-建造者模式

          本文链接:https://www.haomeiwen.com/subject/oxkqnctx.html