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

88 阅读4分钟

这是我参与「第四届青训营 」笔记创作活动的的第6天

什么是设计模式

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

  • 历史经验的总结
  • 与特定语言无关
设计模式背景
  • 《模式语言:城镇、建筑、建造》【1977】
  • 《设计模式:可复用面向对象软件的基础》【1994】
设计模式分类

23种设计模式

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

浏览器中的设计模式

单例模式
定义

全局唯一访问对象

应用场景

缓存,全局状态管理等

用单例模式实现请求缓存
import { api } from "./utils" ;

//定义字面量,缓存为空,全局唯一对象
const cache: Record<string, string> = {};

export const request = async (url: string) => {
  if (cache[url]) { //存在缓存
    return cache[url]; //直接返回
  }

  const response = await api(url);

  cache[url] = response; //写入全局唯一缓存池
  return response;
};
test("should response quickly secona tme", async() => {
  await request("/user/1"); //第一次调用接口
  const startTime = Date.now();
  await request("/user/1"); //第二次调用接口
  const endTime = Date.now();
  
  const costTime = endTime - startTime;
  
  //返回时间50ms,认为已经拿到了缓存池里的内容
  expect(costTime).toBeLessThan(50);
});
发布订阅模式
定义

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

应用场景

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

用发布订阅模式实现用户上线订阅
type Notify = (user: User) => void;

export class User {
  name: string; //用户名称
  status: "offline" | "online"; //状态
  followers: { user: User; notify : Notify }[]; //订阅者信息和上线通知函数
  
  constructor (name: string) { //初始化新的user,传入name
    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);
    });
  }
}
test("should notify followers when user is online for multiple users",() => {
  const user1 = new User("user1");
  const user2 = new User("user2" );
  const user3 = new User("user3");

  const mockNotifyUser1 = jest.fn(); //模拟通知用户1
  const mockNotifyUser2 = jest.fn(); //模拟通知用户2
  
  user1.subscribe(user3,mockNotifyUser1); //用户1订阅了用户3的上线,传入通知用户1的函数
  user2.subscribe(user3,mockNotifyUser2); //用户2订阅了用户3的上线,传入通知用户2的函数
  
  user3.online(); //用户3上线
  
  expect(mockNotifyUser1).toBeCalledWith(user3); //调用通知用户1的函数,传入用户3
  expect(mockNotifyUser2).toBeCalledwith(user3); //调用通知用户2的函数,传入用户3
});

JS中的设计模式

原型模式
定义

复制已有对象来创建新的对象

应用场景

JS中对象创建的基本模式

用原型模式创建上线订阅中的用户
const baseUser: User = { //原型: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: string) => { //创建User

  //基于已有对象baseUser创建user,继承关系
  const user: User = Object.create(baseUser);
  
  user.name = name;
  user.followers = [];
  
  return user;
};
test("should notify followers when user is online for user prototypes",() => {
  const user1 = createUser("user1");
  const user2 = createUser("user2");
  const user3 = createUser("user3");
  //同上······
});
代理模式
定义

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

应用场景

监控,代理工具,前端框架实现等

用代理模式实现用户状态订阅
type Notify = (user : User) void;

export class User {
  //同上···
  
  constructor(name : string) {
    //···
  }
  
  subscribe(user: User, notify: Notify) {
    //···
  }
  
  online() {
    //单一职责原则
    this.status = "online"; //状态变为online
  }
}
export const createProxyUser = (name: string) => {
  const user = new User(name);
  
  const proxyUser = new Proxy(user,{ //创建代理用户,user为需要被代理的对象,set为代理操作
    set: (target, prop: keyof User, value) => { //设置对象属性
      target[prop] = value;
      if (prop ≡ "status") {
        notifyStatusHandlers(target, value); 
      }
      return true;
    },
  });

  const notifyStatusHandlers = (user: User,status: "online" | "offline") => { 
    //处理状态变化
    if (status ≡ "online") {
      user.followers.forEach(({ notify }) => {
        notify(user);
      });
     }
   };

   return proxyUser;
};
迭代器模式
定义

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

应用场景

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

用for of迭代所有组件
clLass MyDomElement {
  tag: string; //传入的标签
  children: MyDomElement[]; //子组件
  constructor(tag: string) {
    this.tag = tag;
    this.children = [];
  }
  
  addChildren(component: MyDomElement) { //添加子组件
    this.children.push(component);
  }

  [Symbol.iterator]() { //使组件变为可迭代
    const list = [...this.children]; //初始化list[子组件]
    let node;
    
    return {
      next:() => { //遍历出所有的组件内容并返回
        while ((node = list.shift())){
          node.children.length > 0 && list.push(...node.children);
          
          //done:迭代是否完成
          return { value: node, done: false };
        }
        return { value: null, done: true };
      },
    };
  }
}
test( "can iterate root element",() => {
  const body = new MyDomElement("body");
  
  const header = new MyDomElement("header");
  
  const main = new MyDomElement("main");
  
  const banner = new MyDomElement("banner");
  const content = new MyDomElement("content");
  
  const footer = new MyDomElement("footer");
  
  //body添加子组件
  body.addChildren(header);
  body.addChildren(main);
  body.addChildren(footer);

  //main添加子组件
  main.addChildren(banner);
  main.addChildren(content);
  
  const expectTags: string[] = [];
  for (const element of body) { //使用for of遍历body
    if (element) {
      expectTags.push(element.tag);
    }
  }

  expect(expectTags.length).toBe(5);
});

前端框架中的设计模式

代理模式
前端框架中对DOM操作的代理
  • 没有框架之前:

WAWXL{%S1II4EBMZYRT6C%R.png

  • 使用框架
    • 看似是我们在更改DOM,实际上是由代理后的DOM完成更新。

image.png

组合模式
定义

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

应用场景

DOM,前端组件,文件目录,部门