前端设计模式应用 | 青训营笔记

60 阅读2分钟

前端设计模式应用 | 青训营笔记

这是我参与【第四届青训营】笔记创作活动的第4天

一、什么是设计模式

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

  • 历史经验的总结
  • 与特定语言无关
二、设计模式分类
23种设计模式
  • 创建型 - 如何创建一个对象
  • 结构性 - 如何灵活的将对象组装成较大的结构
  • 行为型 - 负责对象间的高效通信和职责划分

浏览器中的设计模式

  • 单例模式

    定义:全局唯一访问对象

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

    单例模式实现请求缓存

    test("should response quickly second time", async() ={
      await request("/user/1");
      const startTime = Date.now();
      await request("/user/1");
      const endTime = Date.now();
      const costTime = endTime - startTime;
      expect(costTime).toBeLessThan(50);});
    
  • 发布订阅模式

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

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

 const button = document.getElementById("button"); //button为被定义的对象
const doSomthing1 = () => { //订阅者对象
console.log ("Send message to user");
};
​
const doSomthing2 = () => { //订阅者对象
console.log ("Log... ");
};
​
button.addEventListener("click", doSomthing1);  //函数作为参数
button.addEventListener("click", doSomthing2);
三、JavaScript中的设计模式
  • 原型模式

定义:复制已有对象来创建新的对象

应用场景:JS中对象创建的基本模式

用原型模式创建上线订阅中的用户

test("should notify followers when user is online for user prototypes", () => {
  const user1 = createUser("user1");
  const user2 = createUser("user2");
  const user3 = createUser("user3");
  
  const mockNotifyUser1 = jest.fn();
  const mockNotifyUser2 = jest.fn();
  
  user1.subscribe(user3, mockNotifyUser1);
  user2.subscribe(user3, mockNotifyUser2);
  
  user3.online();
  
  expect(mockNotifyUser1).toBeCalledwith(user3);
  expect(mockNotifyUser2).toBeCalledWith(user3);
  });
  • 代理模式

定义:可自定义控制对象的访问方式,并且允许在更新前后做一些额外处理

应用场景:监控,代理工具,前端框架实现等

export const createProxyUser = (name: string) => {
  const user = new User(name); //先创建一个User
  
  const proxvUser = new Proxy(user,{ //创建代理用户
    set: (target, prop: keyof User, value) => { //set:设置原本对象属性时触发的函数
      target[prop] = value;
      if (prop==="status") {
        notifyStatusHandlers(target,value); //处理状态变化
        }
      return true;
    },
    //get:获取原本对象属性时触发的函数
  });
  
​
  const notifyStatusHandlers = (user: User, status: "online" | "offline") => {
  if (status === "online") {
     user.followers.forEach(({ notify }) => {
       notify(user);
  });
  }
};
​
return proxyUser;
  • 迭代器模式

定义:在不暴露数据类型的情况下访问集合中的数据

应用场景:数据结构中有多种数据类型,列表,树等,提供通用操作接口

用for of 迭代所有组件

test("can iterate root element",() => {
const body = new HyDomElement("body");
​
const header = new HyDomElement("header") ;
​
const main = hew HyDomElenent("main");
​
const banner = new MyDomElement("banner");
const content = new HyDomElement("content");
​
const footer = new HyDomElement("footer") ;
​
body.addChildren(header);
body.addchildren(main);
body.addchildren(footer);
​
main.addChildren(banner);
main.addChildren(content);
​
const expectTags: string[] = [];
for (const element of body) {
  if (element) {
    expectTags.push(element.tag);
    }
  }
  
expect(expectTags.length).toBe(5);H);
四、前端框架中的设计模式
  • 代理模式

image-20220802095332566

  • 组合模式

定义:可多个对象组合使用,也可单个对象独立使用

应用场景:DOM,前端组件,文件目录,部门

\