单例模式实现缓存。
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;
};
发布订阅模式实现用户上线订阅。
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) {
this.followers.push({user,notify});
}
online () {
this.status="online";
this.followers.forEach(({notify}) => {
notify(this);
});
}
}
我们在开发总是或多或少地用过设计模式,把设计模式总结出来,可以提高编程效率。同时,设计模式也忌讳过度设计,我们可以先快速实现需求,再逐渐修改。用好设计模式,需要我们在开发中保持代码质量和设计的意识。