zoukankan      html  css  js  c++  java
  • JS设计模式 -- 4种创建型模式

    1. 工厂模式

    作用:实现对象的批量创建

    /* 构造函数 */
    function Person(name) {
      this.name = name;
    }
    function Car(model) {
      this.model = model;
    }
    /* 创建 */
    function create(type, val) {
      return (this instanceof create) ?
        this[type](val) : new create(type, val);
    }
    create.prototype = {
      person: Person,
      car: Car
    }
    console.log(create('person', 'zhangsan'))
    console.log(new create('car', 'bwm'))
    

    2. 原型模式

    作用:创建一个共享原型,通过拷贝这个原型来创建新的类

    // 也可以是其他类的原型
    let prototype = {
      say() {
        console.log(this.name);
      }
    }
    function Person() {
      function F() { };
      F.prototype = prototype;
      let f = new F();
      f.name = "zhansan";
      return f;
    }
    new Person().say();// zhansan
    

    3. 建造者模式

    作用:将创建对象的细节分为创建子对象的过程,使结构更加清晰

    /* 实现 */
    function Person(name) {
      this.name = name;
    }
    
    function CreateName(name) {
      this.wholeName = name;
      [this.firstName, this.lastName] = name.split(' ');
    }
    
    function CreateWork(workName) {
      switch (workName) {
        case 'engineer':
          this.workName = "工程师";
          this.desc = "热爱编程";
          break;
        case 'teacher':
          this.workName = "老师";
          this.desc = "热爱分享";
          break;
        default:
          this.workName = workName;
          this.desc = "无";
      }
    }
    CreateWork.prototype.changeWork = function (workName, desc) {
      workName && (this.workName = workName);
      desc && (this.desc = desc);
    }
    /* 创建类 */
    function Candidate(params) {
      let _candidate = new Person();
      _candidate.name = new CreateName(params.name);
      _candidate.work = new CreateWork(params.work);
      return _candidate;
    }
    
    /* 举例 */
    let arr = [
      { name: "zhang san", work: "engineer" },
      { name: "li si", work: "teacher" }
    ];
    let candidates = [];
    arr.forEach(v => {
      candidates.push(new Candidate(v));
    })
    console.log(candidates[0]);
    candidates[0].work.changeWork('学生', '热爱学习');
    console.log(candidates[0]);
    

    4. 单例模式

    作用:实现无论创建多少个对象都返回同一个

    const createSingle = (function () {
      let _unique = null;// 私有变量
      return function () {
        if (_unique === null) {
          _unique = { a: 1 };
        }
        return _unique;
      }
    })();
    
    let single1 = createSingle();
    let single2 = createSingle();
    console.log(single1 === single2);// true
    
  • 相关阅读:
    ZOJ 1002 Fire Net
    Uva 12889 One-Two-Three
    URAL 1881 Long problem statement
    URAL 1880 Psych Up's Eigenvalues
    URAL 1877 Bicycle Codes
    URAL 1876 Centipede's Morning
    URAL 1873. GOV Chronicles
    Uva 839 Not so Mobile
    Uva 679 Dropping Balls
    An ac a day,keep wa away
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/13340904.html
Copyright © 2011-2022 走看看