1 2 3 4

设计模式小记

  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 {
        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.

       

       

posted @ 2023-06-02 14:34  无序  阅读(3)  评论(0编辑  收藏  举报