当前位置: 首页 > news >正文

前端设计模式实战:打造可维护的代码架构

前端设计模式实战打造可维护的代码架构前言大家好我是前端老炮儿。今天咱们来聊聊前端设计模式设计模式是软件设计中的经典解决方案掌握设计模式可以让我们写出更优雅、更可维护的代码。但是很多同学学了设计模式却不知道怎么在实际项目中应用。今天我就带大家一起实战前端设计模式看看如何在真实项目中使用它们什么是设计模式设计模式是一套被反复使用、经过分类编目的代码设计经验总结。它可以帮助我们提高代码可复用性增强代码可维护性提升系统稳定性便于团队协作前端常用设计模式1. 单例模式 (Singleton)确保一个类只有一个实例并提供全局访问点。场景全局状态管理、配置管理、工具类class Singleton { private static instance: Singleton | null null private constructor() {} public static getInstance(): Singleton { if (!Singleton.instance) { Singleton.instance new Singleton() } return Singleton.instance } public doSomething(): void { console.log(Doing something...) } } const instance1 Singleton.getInstance() const instance2 Singleton.getInstance() console.log(instance1 instance2) // trueReact中应用class AppState { private static instance: AppState | null null private state: Recordstring, any {} private constructor() {} public static getInstance(): AppState { if (!AppState.instance) { AppState.instance new AppState() } return AppState.instance } public set(key: string, value: any): void { this.state[key] value } public get(key: string): any { return this.state[key] } }2. 工厂模式 (Factory)定义一个创建对象的接口让子类决定实例化哪个类。场景组件创建、服务初始化、数据解析interface Product { name: string price: number } class ConcreteProductA implements Product { name Product A price 100 } class ConcreteProductB implements Product { name Product B price 200 } class ProductFactory { public static create(type: A | B): Product { switch (type) { case A: return new ConcreteProductA() case B: return new ConcreteProductB() default: throw new Error(Unknown product type: ${type}) } } } const productA ProductFactory.create(A) const productB ProductFactory.create(B)React中应用interface ComponentProps { type: button | input | select } class ButtonComponent implements React.FC { render() { return buttonClick me/button } } class InputComponent implements React.FC { render() { return input typetext / } } class ComponentFactory { public static create(type: string): React.FC { switch (type) { case button: return ButtonComponent case input: return InputComponent default: throw new Error(Unknown component type: ${type}) } } }3. 观察者模式 (Observer)定义对象间的一对多依赖当一个对象状态改变时所有依赖它的对象都会收到通知。场景事件系统、状态管理、发布订阅interface Observer { update(data: any): void } class Subject { private observers: Observer[] [] public attach(observer: Observer): void { this.observers.push(observer) } public detach(observer: Observer): void { const index this.observers.indexOf(observer) if (index -1) { this.observers.splice(index, 1) } } public notify(data: any): void { this.observers.forEach(observer observer.update(data)) } } class ConcreteObserver implements Observer { private name: string constructor(name: string) { this.name name } public update(data: any): void { console.log(${this.name} received: ${data}) } } const subject new Subject() const observer1 new ConcreteObserver(Observer 1) const observer2 new ConcreteObserver(Observer 2) subject.attach(observer1) subject.attach(observer2) subject.notify(Hello World)4. 策略模式 (Strategy)定义一系列算法把它们封装起来并且使它们可以相互替换。场景表单验证、排序算法、支付方式interface Strategy { execute(data: number[]): number[] } class BubbleSort implements Strategy { execute(data: number[]): number[] { const arr [...data] for (let i 0; i arr.length; i) { for (let j 0; j arr.length - i - 1; j) { if (arr[j] arr[j 1]) { [arr[j], arr[j 1]] [arr[j 1], arr[j]] } } } return arr } } class QuickSort implements Strategy { execute(data: number[]): number[] { if (data.length 1) return data const pivot data[Math.floor(data.length / 2)] const left data.filter(x x pivot) const middle data.filter(x x pivot) const right data.filter(x x pivot) return [...this.execute(left), ...middle, ...this.execute(right)] } } class Context { private strategy: Strategy constructor(strategy: Strategy) { this.strategy strategy } public setStrategy(strategy: Strategy): void { this.strategy strategy } public executeStrategy(data: number[]): number[] { return this.strategy.execute(data) } } const data [3, 1, 4, 1, 5, 9, 2, 6] const context new Context(new BubbleSort()) console.log(context.executeStrategy(data)) context.setStrategy(new QuickSort()) console.log(context.executeStrategy(data))5. 装饰器模式 (Decorator)动态地给对象添加额外的职责。场景权限控制、日志记录、性能监控interface Component { operation(): string } class ConcreteComponent implements Component { operation(): string { return ConcreteComponent } } class Decorator implements Component { protected component: Component constructor(component: Component) { this.component component } operation(): string { return this.component.operation() } } class ConcreteDecoratorA extends Decorator { operation(): string { return DecoratorA(${super.operation()}) } } class ConcreteDecoratorB extends Decorator { operation(): string { return DecoratorB(${super.operation()}) } } const component new ConcreteComponent() const decoratedA new ConcreteDecoratorA(component) const decoratedB new ConcreteDecoratorB(decoratedA) console.log(decoratedB.operation()) // DecoratorB(DecoratorA(ConcreteComponent))实战案例案例1状态管理系统interface State { handle(context: Context): void } class Context { private state: State constructor(state: State) { this.transitionTo(state) } public transitionTo(state: State): void { this.state state this.state.handle(this) } public request1(): void { this.state.handle(this) } } class ConcreteStateA implements State { handle(context: Context): void { console.log(Handling request in State A) context.transitionTo(new ConcreteStateB()) } } class ConcreteStateB implements State { handle(context: Context): void { console.log(Handling request in State B) context.transitionTo(new ConcreteStateA()) } } const context new Context(new ConcreteStateA()) context.request1() // Handling request in State A context.request1() // Handling request in State B context.request1() // Handling request in State A案例2组件渲染器interface Renderer { render(): string } class HtmlRenderer implements Renderer { render(): string { return divHTML Content/div } } class MarkdownRenderer implements Renderer { render(): string { return # Markdown Content } } class Document { private renderer: Renderer constructor(renderer: Renderer) { this.renderer renderer } public setRenderer(renderer: Renderer): void { this.renderer renderer } public render(): string { return this.renderer.render() } } const document new Document(new HtmlRenderer()) console.log(document.render()) // divHTML Content/div document.setRenderer(new MarkdownRenderer()) console.log(document.render()) // # Markdown Content设计模式选择指南场景推荐模式全局状态管理单例模式对象创建工厂模式事件通知观察者模式算法切换策略模式功能增强装饰器模式状态切换状态模式对象组合组合模式接口适配适配器模式最佳实践1. 不要过度设计设计模式是工具不是银弹。不要为了使用模式而使用模式。2. 遵循SOLID原则Single Responsibility单一职责Open/Closed开闭原则Liskov Substitution里氏替换Interface Segregation接口隔离Dependency Inversion依赖倒置3. 结合框架特性React的Hooks、Vue的Composition API都有自己的模式要学会结合使用。4. 保持代码简洁设计模式的目的是让代码更清晰而不是更复杂。总结通过今天的学习我们了解了单例模式确保唯一实例工厂模式封装对象创建观察者模式实现发布订阅策略模式动态切换算法装饰器模式动态增强功能设计模式是程序员的内功心法掌握它们可以让我们写出更优雅、更可维护的代码。但是记住设计模式不是教条要灵活运用最后给大家留个思考题在你的项目中哪些地方可以应用设计模式来改进代码欢迎在评论区留言讨论
http://www.gsyq.cn/news/1343357.html

相关文章:

  • 2026年5月主流电竞鼠标品牌十大排行榜推荐:夜战防延迟评测专业价格 - 品牌推荐
  • Midjourney景深模糊失效全解析,深度拆解--no参数干扰链、背景层剥离阈值及alpha通道注入技巧
  • Verdi波形调试避坑指南:从fsdb文件加载失败到状态机可视化的完整排错流程
  • AI Agent重构开发工具链:从代码补全到闭环执行
  • 大模型4-bit量化实战:精度、速度与部署的工程平衡
  • 别再让模型过拟合了!PyTorch实战:用Weight Decay(权重衰减)驯服你的神经网络
  • 2026年质量好的温州彩色吸塑包装/对折吸塑包装/日用品吸塑包装优质厂家汇总推荐 - 品牌宣传支持者
  • 别再手动开两个终端了!群晖Docker部署MCSM面板后,配置Systemd服务实现开机自启动详解
  • 2026年比较好的温州加急吸塑包装/吸塑包装优质供应商推荐 - 行业平台推荐
  • 2026年质量好的薄壁高难度吸塑定制/温州特殊纹路吸塑定制/吸塑定制厂家综合对比分析 - 行业平台推荐
  • 通过用量看板分析不同模型在taotoken上的实际token消耗差异
  • 保姆级教程:在RK3588开发板上用Python部署NanoTrack,实测120FPS真香
  • 2026年知名的机房钢网桥架/镇江防腐钢网桥架/不锈钢钢网桥架/镀锌钢网桥架公司选择指南 - 品牌宣传支持者
  • JLink版本不兼容?手把手教你解决APM32F003F6P6在Keil V5.14下的烧写闪退与报错
  • 2026年口碑好的湖北工厂化养虾设备全套/湖北养虾设备/工厂化养虾设备全套/养虾设备高口碑品牌推荐 - 行业平台推荐
  • 不用魔法!国内网络环境搞定Langchain-Chatchat本地部署(附模型离线包)
  • 每日热门skill:MCP Filesystem Server:AI时代的文件系统管家,让代码操控如臂使指,首个实现AI直接操作系统文件的工具,将开发效率提升10倍
  • Prediction、Generation、Inference:企业AI工具选型的三大技术范式
  • SerDes技术解析:从并行到串行的高速数据通信核心
  • 四旋翼DIY实战:用STM32和ICM20602实现Mahony姿态解算(附完整代码)
  • 从Windows COM到现代C++:聊聊动态库接口设计的‘版本管理’艺术
  • java springboot-vue框架的避暑山庄数字博物馆
  • Win11系统下,Java开发环境配置保姆级教程(JDK 8u201安装+环境变量避坑指南)
  • MoE混合专家架构:大模型高效推理的核心原理与实战
  • java springboot-vue框架的经园小区物业信息管理系统的设计与实现
  • RLHF工程化实践:用合成反馈替代人工标注的完整闭环
  • 基于角色扮演的模拟环境:用Multi-Agent进行产品策略推演与压力测试
  • RK3568嵌入式Linux驱动开发实战:从内核模块到设备树与中断处理
  • 告别手动操作!用Python脚本批量导入导出NX/UG零件,还能一键移除参数
  • AI模型能力演进与受控发布机制解析