前端开发中的一场「交通革命」——小明与面向对象的故事
第一章:初识面向对象
前端工程师小明接到一个需求:开发交互式交通信号灯管理系统,要求每个信号灯能独立切换红、黄、绿三色,且支持动态增减数量。面对看似复杂的逻辑,小明决定采用 面向对象编程(OOP) 方案:
class TrafficLight { constructor(id) { this.id = id; // 唯一标识 :ml-citation{ref="1" data="citationList"} this.color = 'red'; // 初始状态 this.dom = this.#createDOM(); // 封装DOM构建逻辑 :ml-citation{ref="1,5" data="citationList"} this.bindEvents(); } // 私有方法:构建DOM元素 :ml-citation{ref="5" data="citationList"} #createDOM() { const div = document.createElement('div'); div.className = 'traffic-light'; div.dataset.color = this.color; return div; } // 事件绑定:点击切换颜色 bindEvents() { this.dom.addEventListener('click', () => this.changeColor()); } // 状态切换方法 changeColor() { const colors = ['red', 'yellow', 'green']; const currentIndex = colors.indexOf(this.color); this.color = colors[(currentIndex + 1) % 3]; this.dom.dataset.color = this.color; // 同步UI状态 :ml-citation{ref="1" data="citationList"} } }
第二章:工厂模式实战
为了实现 批量生成100个信号灯,小明采用 工厂模式 优化代码:
class TrafficLightFactory { static createLights(count) { return Array.from({ length: count }, (_, i) => new TrafficLight(`light-${i + 1}`) ); } } // 初始化场景 const lights = TrafficLightFactory.createLights(100); document.body.append(...lights.map(light => light.dom));
通过工厂类统一管理实例,代码可维护性显著提升
第三章:状态管理进阶
随着需求升级,小明引入 状态模式 应对复杂规则:
const StateManager = { transitions: new Map([ ['red', { next: 'yellow', timeout: 3000 }], ['yellow', { next: 'green', timeout: 1000 }], ['green', { next: 'red', timeout: 5000 }] ]), getNextState(current) { return this.transitions.get(current)?.next || 'red'; } }; // 扩展TrafficLight类方法 changeColor() { this.color = StateManager.getNextState(this.color); this.#updateUI(); }
将状态转换规则独立管理,符合 开闭原则
第四章:继承与多态
当用户提出 夜间模式 需求时,小明通过继承实现功能扩展:
class NightTrafficLight extends TrafficLight { changeColor() { super.changeColor(); this.#enableBlinkEffect(); // 新增夜间闪烁特效 } #enableBlinkEffect() { this.dom.classList.add('night-mode'); } }
子类复用父类核心逻辑,同时扩展新特性,体现 多态思想
项目总结
通过这个项目,小明深刻体会到面向对象在前端的价值:
这场「交通革命」最终获得用户高度评价,小明也晋升为项目主程。他用实践证明:面向对象不是纸上谈兵,而是解决复杂前端工程问题的利器