Day 09 前端设计模式 | 青训营

79 阅读2分钟

一、什么是设计模式?

软件设计中常见问题的解决方案模型

  • 历史经验的总结
  • 与特定语言无关

设计模式背景

  1. 模式语言:城镇、建筑、建造 (A Pattern Language: Towns, Buildings, Construction) 1977
  2. 设计模式:可复用面向对象软件的基础 (Design Patterns: Elements of Reusable Object-Oriented Software) 1994

设计模式分类

23种设计模式

  • 创建型 - 如何创建一个对象
  • 结构型 - 如何灵活的将对象组装成较大的结构
  • 行为型 - 负责对象间的高效通信和职责划分

二、浏览器中的设计模式

单列模式

- 定义 : 全局唯一访问对象

- 应用场景 : 缓存,全局状态管理等

用单列模式实现请求缓存

静态方法(getInstance) :

static getInstance() {
    if (this.instance) {
        return this.instance;
    }

    this.instance = new Request();
    return this.instance;
}

如果instance存在就返回它,如果不存在就新建一个instanc并返回。

发布订阅模式

- 定义 : 一种订阅机制,可在被订阅对象发生变化时通知订阅者。

- 应用场景 : 从系统架构之间的解耦,到业务中一些实现模式,像邮件订阅,上线订阅等等,应用广泛。

如:

1. 用发布订阅模式绑定按钮

const button = document.getElementBtId("button");

const doSomting1 = () => {
console.log("Send message to user");
};

const doSomting2 = () => {
    console.log("Log...");
    };

button.addEventListener("click", doSomting1);
button.addEventListener("click", doSomting2);
// ...

2. 用发布订阅模式实现用户上线订阅

type Notify = (user: User) => void;

export class User {
    name: string;
    status: "offline" | "online";
    followers: { user: User;ontify: Notify }[];

    constructor(name: string) {
        this.name = name;
        this.status = "offline";
        this.followers = [];
    }

    subscribe(user: User, notify: Notify) {
        user.followers.push({ user, notify });
    }

    online() {
        this.status = "online";

        this.followers.forEach(({ notify }) => {
            notify(this);
        });
    }
}

小节

1.前端设计模式基本情况

1.1 设计模式定义

1.2 设计模式背景同步

1.3 设计模式发展趋势

1.4 设计模式分类

2.浏览器中的设计模式

2.1 单例模式

2.2 发布订阅模式

设计模式并不复杂,重要的是其思维模式以及在不同编程语言及场景下的应用