设计模式小记

发布时间 2023-06-02 14:36:27作者: 无序
  1. 创建型模式(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

       

  2. 结构型模式(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.

       

  3. 行为型模式(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 {
        execute() {
          throw new Error('execute() must be implemented.');
        }
      }
      
      class ConcreteCommand extends Command {
        constructor(receiver) {
          super();
          this.receiver = receiver;
        }
      
        execute() {
          this.receiver.action();
        }
      }
      
      class Receiver {
        action() {
          console.log('Receiver executes action.');
        }
      }
      
      class Invoker {
        setCommand(command) {
          this.command = command;
        }
      
        executeCommand() {
          this.command.execute();
        }
      }
      
      // 使用命令模式执行命令
      const receiver = new Receiver();
      const command = new ConcreteCommand(receiver);
      const invoker = new Invoker();
      
      invoker.setCommand(command);
      invoker.executeCommand();
      // 输出: Receiver executes action.