[前端与HTML]--前端设计模式应用

147 阅读3分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 16 天


1.什么是设计模式

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

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

1.2设计模式背景

  1. 模式语言:城镇、建筑、建造
  2. 设计模式:可复用面向对象软件的基础

1.3设计模式分类

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

1.4浏览器中的设计模式

  • 单例模式
  • 发布订阅模式
单例模式

定义:全局唯一访问对象

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

用单例模式实现请求缓存
    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;
                    };
    text("should response quickly second time",async()=>{
        await request("/user/1");
        const startTime=Date.now();
        await request("/user/1");
        const endTime=date.now();
        const constTime=endTime-startTime;
        expect(constTime).toBeLessThan(500);
        });
发布订阅模式

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

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

用发布订阅模式实现用户上线订阅
    type Notify=(user: User)=>void;
    
    export class User{
        name:string;
        status:"offline" | "online";
        followers:{user: User; notify: 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);
        });
       }
      }
    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();
    const mockNotifyUser2=jest.fn();
    
    User1.subscript(user3,mockNotifyUser1);
    User2.subscript(user3,mockNotifyUser2);
    
    user3.online();
    
    expect(mockNotifyUser1).toBeCalledWith(user3);
    expect(mockNotifyUser2).toBeCalledWith(user3);
    });

2.JavaScript中的设计模式

  • 原型模式
  • 代理模式
  • 迭代器模式

2.1原型模式

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

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

用原型模式创建上线阅读中的用户
    const baseUser: User={
        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)=>{
              const user: User= Object.create(baseUser);
              
              user.name=name;
              user.followers=[];
              
              return user;
              };
test("should notify followers when user is online foruser prototypes",()=>{
    const user1=new User("user1");
    const user2=new User("user2");
    const user3=new User("user3");
    
    const mockNotifyUser1=jest.fn();
    const mockNotifyUser2=jest.fn();
    
    User1.subscript(user3,mockNotifyUser1);
    User2.subscript(user3,mockNotifyUser2);
    
    user3.online();
    
    expect(mockNotifyUser1).toBeCalledWith(user3);
    expect(mockNotifyUser2).toBeCalledWith(user3);
    });

2.2代理模式

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

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

使用代理模式实现用户状态订阅
    type Notify=(user: User)=>void;
    
    export class User{
        name:string;
        status:"offline" | "online";
        followers:{user: User; notify: 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);
        });
       }
      }
    type Notify=(user: User)=>void;
    
   class User{
        name:string;
        status:"offline" | "online";
        followers:{user: User; notify: 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";             
       }
      }
    export const createProxyUser=(name:string_=>{
        const user=new User(name);
        
        const proxyUser = new Proxy(user,{
        set:(target,prap:keyof User,value)=>{
            target[prop]=value;
            if(prap ≡ "status"){
            notifyStatusHandlers(target,value);
            }
            return true;
            }
            })
            
            const notifyStatusHandlers=(user:User,status:"online" | "offline")=>{
            if(status ≡ "online"){
            user.followers.forEach(({notify})=>{
            notify(user);
            })
           }
          };
          return proxyUser;
          };

2.3迭代器模式

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

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

用for of迭代所有组件
    class MyDomElement{
     tag:string;
     children:MyDomElement[];
     constructor(tag:string){
     this.tag=tag;
     this.children=[];
     }
     addchildren(component:MyDomElement){
         this.children.push(component);
         }
        }