设计模式小记
-
创建型模式(Creational Patterns):
- 工厂模式(Factory Pattern):就像是一个生产线,根据需要创建不同类型的产品,隐藏了产品的具体制造过程。例如,一个按钮工厂可以根据类型创建不同样式的按钮。
// 简单工厂模式 class ButtonFactory { createButton(type) { switch (type) { case 'submit': return new SubmitButton(); case 'cancel': return new CancelButton(); default: throw new Error('Invalid button type'); } } } class SubmitButton { render() { console.log('Rendered a submit button.'); } } class CancelButton { render() { console.log('Rendered a cancel button.'); } } // 使用工厂创建按钮 const factory = new ButtonFactory(); const submitButton = factory.createButton('submit'); submitButton.render(); // 输出:Rendered a submit button.
- 单例模式(Singleton Pattern):就像是一个房间只能有一个人进入,确保一个类只有一个实例。例如,在应用程序中创建一个全局状态管理器,保证只有一个实例来管理状态。
// 单例模式示例 class Logger { constructor() { if (!Logger.instance) { Logger.instance = this; } return Logger.instance; } log(message) { console.log(message); } } // 创建实例 const logger1 = new Logger(); const logger2 = new Logger(); console.log(logger1 === logger2); // 输出:true logger1.log('Hello World'); // 输出:Hello World
- 工厂模式(Factory Pattern):就像是一个生产线,根据需要创建不同类型的产品,隐藏了产品的具体制造过程。例如,一个按钮工厂可以根据类型创建不同样式的按钮。
-
结构型模式(Structural Patterns):
- 适配器模式(Adapter Pattern):就像是使用一个适配器来兼容不同种类的插头,将一个接口转换成另一个接口,使得原本不兼容的对象可以协同工作。例如,适配器可以将不同版本的接口统一起来供客户端使用。
// 适配器模式示例 class OldApi { request() { return 'Response from the old API'; } } class NewApi { fetch() { return 'Response from the new API'; } } class ApiAdapter { constructor() { this.newApi = new NewApi(); } request() { return this.newApi.fetch(); } } // 使用适配器调用旧的API const adapter = new ApiAdapter(); const response = adapter.request(); console.log(response); // 输出:Response from the new API
- 装饰器模式(Decorator Pattern):就像是在一个装饰房间的过程中,逐步地添加新的装饰物,而不改变房间本身。装饰器模式可以动态地给对象添加额外的功能,而不需要修改其原始代码。例如,可以通过装饰器为一个组件添加日志记录的功能。
// 装饰器模式示例 class Component { operation() { console.log('Component operation.'); } } class Decorator { constructor(component) { this.component = component; } operation() { this.component.operation(); this.additionalOperation(); } additionalOperation() { console.log('Decorator additional operation.'); } } // 使用装饰器增加额外的功能 const component = new Component(); const decoratedComponent = new Decorator(component); decoratedComponent.operation(); // 输出: // Component operation. // Decorator additional operation.
- 适配器模式(Adapter Pattern):就像是使用一个适配器来兼容不同种类的插头,将一个接口转换成另一个接口,使得原本不兼容的对象可以协同工作。例如,适配器可以将不同版本的接口统一起来供客户端使用。
-
行为型模式(Behavioral Patterns):
- 观察者模式(Observer Pattern):就像是订阅报纸一样,多个观察者对象订阅了一个主题对象,当主题对象发生变化时,观察者对象都会收到通知并做出相应的反应。例如,可以使用观察者模式来实现事件的订阅和发布功能。
// 观察者模式示例 class Subject { constructor() { this.observers = []; } addObserver(observer) { this.observers.push(observer); } removeObserver(observer) { this.observers = this.observers.filter((obs) => obs !== observer); } notifyObservers(data) { this.observers.forEach((observer) => observer.update(data)); } } class Observer { update(data) { console.log(`Received data: ${data}`); } } // 使用观察者模式 const subject = new Subject(); const observer1 = new Observer(); const observer2 = new Observer(); subject.addObserver(observer1); subject.addObserver(observer2); subject.notifyObservers('Hello observers!'); // 输出: // Received data: Hello observers! // Received data: Hello observers! subject.removeObserver(observer2); subject.notifyObservers('Goodbye observers!'); // 输出: // Received data: Goodbye observers!
- 命令模式(Command Pattern):就像是将一个请求封装成一个对象,使得可以将请求的执行延迟、排队、参数化等。例如,将用户的操作封装为一个命令对象,可以实现撤销、重做等功能。
// 命令模式示例 - 将请求封装成对象 class Command { constructor(receiver) { this.receiver = receiver; } execute() { throw new Error('execute() must be implemented.'); } } class ConcreteCommandA extends Command { execute() { this.receiver.actionA(); } } class ConcreteCommandB extends Command { execute() { this.receiver.actionB(); } } class Receiver { actionA() { console.log('Receiver executes Action A.'); } actionB() { console.log('Receiver executes Action B.'); } } class Invoker { constructor() { this.commands = []; } setCommand(command) { this.commands.push(command); } executeCommands() { this.commands.forEach((command) => command.execute()); this.commands = []; } } // 使用命令模式将请求封装成对象 const receiver = new Receiver(); const commandA = new ConcreteCommandA(receiver); const commandB = new ConcreteCommandB(receiver); const invoker = new Invoker(); invoker.setCommand(commandA); invoker.setCommand(commandB); invoker.executeCommands(); // 输出: // Receiver executes Action A. // Receiver executes Action B.
- 观察者模式(Observer Pattern):就像是订阅报纸一样,多个观察者对象订阅了一个主题对象,当主题对象发生变化时,观察者对象都会收到通知并做出相应的反应。例如,可以使用观察者模式来实现事件的订阅和发布功能。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律