• 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
    
  • 相关阅读:
    webyestem(伊莱博)票据管理(ver1.0)数据库设计
    MicrosoftNorthwind(电子商务)数据库设计
    WebForm三层架构
    WebForm带接口工厂模式的三层架构
    VS 2008 C#代码调试进C++代码设置/远程调试
    C# 中使用指针
    互操作性——使用C/C++类型的非托管函数基础
    Perforce使用指南_forP4V
    [转]DotNet程序之找BUG心得
    C# 对XML基本操作总结
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/13340904.html
Copyright © 2020-2023  润新知