• js建筑者模式


    http://www.manongjc.com/article/42740.html

    // //书籍建造者类
    // class BookBuilder {
    //   constructor() {
    //     this.name = "";
    //     this.author = "";
    //     this.price = 0;
    //     this.category = "";
    //     Object.keys(this).forEach((key) => {
    //       const withName = `with${key.substring(0, 1).toUpperCase()}${key.substring(
    //         1
    //       )}`;
    //       this[withName] = (value) => {
    //         this[key] = value;
    //         return this;
    //       };
    //     });
    //   }
    
    //   //调用建造者
    //   build() {
    //     const keysNoWithers = Object.keys(this).filter(
    //       (key) => typeof this[key] !== "function"
    //     );
    //     return keysNoWithers.reduce((returnValue, key) => {
    //       console.log("returnValue", returnValue);
    //       return {
    //         ...returnValue,
    //         [key]: this[key],
    //       };
    //     }, {});
    //   }
    // }
    class BaseBuilder {
      init() {
        Object.keys(this).forEach((key) => {
          const withName = `with${key.substring(0, 1).toUpperCase()}${key.substring(
            1
          )}`;
          this[withName] = (value) => {
            this[key] = value;
            return this;
          };
        });
      }
      build() {
        const keysNoWithers = Object.keys(this).filter(
          (key) => typeof this[key] !== "function"
        );
    
        return keysNoWithers.reduce((returnValue, key) => {
          return {
            ...returnValue,
            [key]: this[key],
          };
        }, {});
      }
    }
    
    //子类1: 书籍建造者类
    class BookBuilder extends BaseBuilder {
      constructor() {
        super();
        this.name = "";
        this.author = "";
        this.price = 0;
        this.category = "";
    
        super.init();
      }
    }
    
    //子类2: 印刷厂建造者类
    class printHouseBuilder extends BaseBuilder {
      constructor() {
        super();
    
        this.name = "";
        this.location = "";
        this.quality = "";
    
        super.init();
      }
    }
    
    //调用印刷厂建造类
    const printHouse = new printHouseBuilder()
      .withName("新华印刷厂")
      .withLocation("北京海淀区")
      .withQuality("A")
      .build();
    const book = new BookBuilder()
      .withName("高效能人士的七个习惯")
      .withAuthor("史蒂芬·柯维")
      .withPrice(51)
      .withCategory("励志")
      .build();
    console.log("book", book);

    https://www.cnblogs.com/10manongit/p/12794935.html

  • 相关阅读:
    20200213 超级聊天术
    20220210 java.util.Properties
    20220210 java.util.concurrent.BlockingQueue 方法说明
    20220210 java.util.Queue
    20220210 java.lang.Long
    20220210 Java 反射基础类
    一组很有意思的Principles
    python logging用法的简单总结
    好好的Typora收费了!_2022_01_20
    一些常用的jQuery方法1_20220128
  • 原文地址:https://www.cnblogs.com/TTblog5/p/13130934.html
Copyright © 2020-2023  润新知