继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【十月打卡】第70天 前端常用的7种设计模式(6)

康遇
关注TA
已关注
手记 76
粉丝 3
获赞 9

工厂模式

概念

工厂模式把创建对象或者实例的方法进行统一封装处理,不再需要每次自己创建。
一般遇到new class的场景,可以尝试考虑使用工厂模式。

代码演示和UML类图

  • 符合开放封闭原则(工厂和类相互独立不耦合,可以对工厂或者类进行扩展)
  • 符合依赖倒置原则(工厂依赖IPerson接口,不依赖具体的类,更方便扩展)

代码演示:

interface IPerson {
  name: string;
  speak(): void;
}

class Teacher implements IPerson {
  constructor(public name: string) {}
  speak() {
    console.log(`${this.name}老师说话`);
  }
}

class Student implements IPerson {
  constructor(public name: string) {}
  speak() {
    console.log(`${this.name}同学说话`);
  }
}

class Parent implements IPerson {
  constructor(public name: string) {}
  speak() {
    console.log(`${this.name}家长说话`);
  }
}

function create(type: string, name: string): IPerson {
  if (type === 'student') {
    return new Student(name);
  }
  if (type === 'teacher') {
    return new Teacher(name);
  }
  if (type === 'parent') {
    return new Parent(name);
  }

  throw new Error('输入的参数不正确');
}

const p1 = create('student', '小明');
const p2 = create('teacher', '王皓');
const p3 = create('parent', '田雨');
p1.speak();
p2.speak();
p3.speak();

UML类图:

图片描述

应用场景

  • jQuery
  • Vue
  • React createElement

jQuery

如下伪代码示例:

// 扩展window属性
declare interface Window {
  $: (selector: string) => JQuery;
}

class JQuery {
  constructor(selector: string) {
    const arr: any[] = [...document.querySelectorAll(selector)];
    arr.forEach((item, index) => {
      // @ts-ignore
      this[index] = item;
    });
  }

  removeClass() {
    //...
    return this;
  }

  addClass() {
    //...
    return this;
  }
}

function $(selector: string) {
  return new JQuery(selector);
}

window.$ = $;
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP