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
    
  • 相关阅读:
    【开发笔记】- Linux命令大全
    【面试突击】- SpringMVC那些事(一)
    【阿里云开发】- 搭建和卸载svn服务器
    【阿里云开发】- 安装tomcat
    SpringCloud之Eureka服务发现和注册(二)
    springcloud之环境工程模块(一)
    java多线程中篇(三) —— 线程的控制(创建,运行,阻塞,中断,结束)
    java多线程中篇(二) —— 线程的创建和Synchronized锁关键字
    java多线程中篇(一) —— Thread详情
    JUC之AbstractQueuedSynchronizer原理分析
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/13340904.html
Copyright © 2011-2022 走看看