首页 > 其他分享 >设计模式小记

设计模式小记

时间:2023-06-02 14:46:16浏览次数:36  
标签:const log console observers new 设计模式 class 小记

  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.

       

标签:const,log,console,observers,new,设计模式,class,小记
From: https://www.cnblogs.com/wuxu-dl/p/17451692.html

相关文章

  • go-shadowsw问题小记
    Golangshadows是指在Go语言中,一个变量在内部作用域中被另一个同名同类型的变量声明而隐藏的情况。这种情况可能导致一些意想不到的结果,比如返回错误的值或者引用错误的变量。1funcBadRead(f*os.File,buf[]byte)errerror{2for{3n,err:=f.Read(bu......
  • 设计模式详解之抽象工厂模式--企业的运行模式
    前言本文主要讲述设计模式中的抽象工厂模式,文中使用通俗易懂的案例,使你更好的学习本章知识点并理解原理,做到有道无术。一.什么是抽象工厂模式抽象工厂是23种设计模式中创建型模式的一种,抽象工厂是由多个工厂组合而成。上一章我们提到的工厂模式只存在一个抽象角色,而抽象工厂是......
  • golang实现设计模式之享元模式总结-代码、优缺点、适用场景
    享元模式是一种结构型的设计模式,通过共享细粒度对象实现对象的复用,从而达到减少对象创建与销毁,减少内存消耗,其本质是本质是缓存共享对象,降低内存消耗。享元模式的定义提出了两个要求,细粒度和共享对象。因为要求细粒度,所以不可避免地会使对象数量多且性质相近,此时我们就将这些对象......
  • Java设计模式之单例模式
    一、何谓单例模式?单例模式,也叫单子模式,是一种常用的软件设计模式,属于创建型模式的一种。在应用这个模式时,单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。比如在某个服务器程序中,该服务器的配置信息存放在一......
  • javascript设计模式-责任链
    责任链可以用来消除请求的发送者和接收者之间的耦合,这是通过实现一个由隐式地对请求进行处理的对象组成的链而做到的。链中的每个对象可以处理请求,也可以将其传给下一个对象。JS内部就使用了这种模式来处一事件捕获和冒泡问题。一般的结构如下:发送者知道链中的第一个接收者,它向这个......
  • Vue3 尝试小记
    1.安装vue使用npm或yarn安装Vue3:#npmnpminstallvue@next#yarnyarnaddvue@next2.创建项目文件夹在命令行中,输入以下命令,在根目录下创建一个项目文件夹:mkdirmy-vue3-project3.初始化package.json使用npminit命令,在该目录中创建package.json文件:npm......
  • golang实现设计模式之构建者模式总结-代码、优缺点、适用场景
    构建者模式也是一种创建型的设计模式,该模式将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的对象。大白话就是,构建者模式,从输出角度看依然是创建个对象实例,但是构建者模式更关注创建的细节,或者说一个对象的创建可以拆分为多个步骤,所有的步骤完成才创建出这个对......
  • Go设计模式
    Go-设计模式整理参考:Go设计模式24-总结(更新完毕)-Mohuishou(lailin.xyz)go设计模式实现,包含23种常见的设计模式实现设计模式学习的重点是什么?设计原则,以及设计模式的使用场景和优缺点,实现相对来说还没有那么重要如果是常见的设计模式是武术招式,那么设计原则就是内......
  • Java 微服务中的聚合器设计模式示例
    微服务架构中的聚合器设计模式是一种设计模式,用于通过聚合多个独立的微服务的响应来组成一个复杂的服务。它也是与SAGA、CQRS和EventSourcing一起的基本微服务设计模式之一。当客户端请求需要跨多个微服务分布的数据或功能时,此模式是合适的。可以提高系统的性能和可扩展性通过允许......
  • 什么是微服务中的断路器设计模式?如何实施?
    大家好,微服务设计模式是Java开发人员需要学习的非常重要的概念,不仅是为了创建一个健壮的、可扩展的、高性能的微服务架构,也是为了在Java开发人员面试中取得好成绩。过去,我分享了几种微服务设计模式,如eEventSourcing、SAGA、DatabasePerMicroservices、CQRS、APIGateway......