前端中的设计模式 | 青训营笔记

73 阅读3分钟

文章第一句话为“这是我参与「第四届青训营 」笔记创作活动的第5天

本文主要记录由吴立宁老师讲述的“前端设计模式应用”课程。 23种设计模式。

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

浏览器中的设计模式

单例模式

定义:全局唯一访问对象,像是浏览器中的window 应用场景:缓存,全局状态管理

下面是实现一个全局唯一的请求实例Request,在使用时先获取这个唯一实例然后调用方法即可,这样实现的请求实例是全局唯一的

static是类中的标识,其标记的参数和函数被称作静态参数或函数,它往往用来实现通用应用,不应该被某个实例调用,应该使用类直接使用Request.getInstance

export class Request {
	static instance;  // 全局唯一实例

	// 获取全局唯一实例
	static getInstance() {
            if (this.instance) {
                    return this.instance;
            }
            this.instance = new Request();
            return this.instance;
	}

	async request(url) {
            // 发送请求...
	}
}

// 使用方法
const request = Request.getInstance();
await request.request("/api/1");

发布订阅模式

定义:一种订阅机制,可在被订阅对象发生变化时通知订阅者 应用场景:从系统架构之间的解耦,到业务中一些实现模式,像邮件订阅,上线订阅等等,应用广泛

fllowers是一个数组用来存储订阅了该user的其它user

online在该user上线时,它会遍历flowers,调用订阅者的通知函数

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

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

    online() {
        this.status = "online";
        console.log(this.name + " 上线");

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

const user1 = new User("user1");
const user2 = new User("user2");
const user3 = new User("user3");

user1.subscribe(user3, () => {
	console.log("user1 收到");
});
user2.subscribe(user3, () => {
	console.log("user2 收到");
});

user3.online();
// user3 上线
// user1 收到
// user2 收到

JS中的设计模式

原型模式

定义:复制已有对象来创建新的对象 应用场景:js中对象创建的基本模式

根据这个示例,baseUser就像是一个基线,createUser中主要是利用Object.create拷贝了一份baseUser然后进行个性化的设置

const baseUser = {
    name: "",
    status: "offline",
    followers: [],

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

    online() {
        (this.status = "online"),
        this.followers.forEach(({ notify }) => {
                notify(this);
        });
    },
};

export const createUser = (name) => {
    const user = Object.create(baseUser);

    user.name = name;
    user.followers = [];

    return user;
};

代理模式

定义:可自定义对原对象的访问方式,并且允许在更新前后做一些额外处理 应用场景:监控,代理工具,前端框架的实现

这个实例中使用proxy来实现了类似于发布订阅者模式的功能,当user的属性更改时,如果发生了status状态变化,就会去通知订阅者执行notify函数

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

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

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

export const createProxyUser = (name) => {
    const user = new User(name);

    const proxyUser = new Proxy(user, {
        set: (target, prop, value) => {
            target[prop] = value;
            if (prop === "status") {
                notifyStatusHandlers();
            }
        },
    });

    const notifyStatusHandlers = (user, status) => {
        if (status === "online") {
            user.followers.forEach(({ notify }) => {
                notify(user);
            });
        }
    };

    return proxyUser;
};

迭代器模式

定义:在不暴露数据类型的情况下访问集合中的数据 应用场景:数据结构中有多种数据类型,列表,树等,提供通用操作接口

for of