详细介绍:js 设计模式

介绍一些高频使用的设计模式

  • 创建型模式(解决对象创建问题)

    • 工厂模式
      将对象的创建过程封装在函数或者类中,客户端只关注对象的使用而非创建过程

      //这里相当于一个支付工厂类,并符合开闭原则
      class Payment {
      constructor() {
      this.payClass = {};
      }
      registerPay(type, PayClass) {
      if (!this.payClass[type]) this.payClass[type] = PayClass;
      }
      createPay(type) {
      return new this.payClass[type];
      }
      pay() {
      throw new Error("需要实现pay 方法");
      }
      }
      class AliPay extends Payment {
      pay() {
      console.log("支付宝支付");
      }
      getPrice() {
      return 10;
      }
      }
      const payment = new Payment();
      payment.registerPay("alipay", AliPay);
      const alipay = payment.createPay("alipay");
      console.log(alipay.getPrice());
    • 单例模式
      一个类只有一个实例, 提供全局访问点
      例子类似与 vuex / redux等全局状态管理等就是单例模式

      //实现一个全局的存储管理实例
      class StorageManage {
      setStorage(key,value) {
      localStorage.setItem(key, value);
      }
      getStorage(key) {
      let result = localStorage.getItem(key);
      if(result){
      return JSON.parse(result);
      }
      }
      removeStorage(key) {
      localStorage.removeItem(key);
      }
      clearStorage() {
      localStorage.clear();
      }
      }
      export default new Global();
    • 建造者模式
      建造者模式把复杂的构建步骤抽象出来,分成多个简单的对象来构建

      class ProductBuilder {
      constructor() {
      this.name = "";
      this.skin = "";
      this.price = 0;
      }
      setName(name) { this.name = name; return this; }
      setSkin(skin) { this.skin = skin; return this; }
      setPrice(price) { this.price = price; return this; }
      build() { return new Product(this.name, this.skin, this.price); }
      }
      class Product {
      constructor(name, skin, price) {
      this.name = name;
      this.skin = skin;
      this.price = price;
      }
      }
      const product = new ProductBuilder()
      .setName("xx")
      .setSkin("皮肤A")
      .setPrice(120)
      .build();
      console.log(product);
    • 原型模式
      通过复制已有对象来获取新对象,避免重新创建,减少开销

      const obj = {name: '张三',getName:function () {console.log(this.name)}}
      const obj1 = Object.create(obj)
      obj1.name = '李四'
      console.log(obj.getName())
      console.log(obj1.getName())
  • 结构型模式
    对象与对象之间的组合,以形成更灵活、可扩展的系统结构

    • 装饰器模式
      在不修改原对象的基础上,添加/增强对象的功能
      // 函数装饰器
      function sayHello() {
      console.log('hello')
      }
      function withLogging(fn) {
      return function (...args) {
      console.log('hi') //例如这里增加了其他功能
      return fn.apply(this, args)
      }
      }
      sayHello = withLogging(sayHello)
      sayHello()
    • 代理模式
      代理对象控制对目标对象的访问
      //使用proxy 代理
      const target = {name: '张三'}
      const proxy = new Proxy(target, {
      get(obj, prop) {
      return obj[prop]
      }
      set(obj, prop, value) {
      obj[prop] = value;
      return true
      }
      })
    • 适配器模式
      兼容数据/接口等转为需要的数据/接口
      //适配api 接口数据
      const objArr = [{id: 1, time: new Date().getTime()}]
      const adapter = (arr) => {
      return arr.map(item => {
      return {
      ...item,
      time: moment(objArr ).format('YY-MM-DD')
      }
      })
      }
  • 行为型模式

    • 观察者
      形成一对多的依赖关系,状态发生变更通知所有观察者 例如React Redux的实现
      class Subject {
      constructor() {
      this.state = 0; //状态
      this.observers = [] //观察者集合
      }
      // 添加观察者
      addObserver(observer) {
      this.observers.push(observer)
      }
      // 发布状态 
      setState(state) {
      this.state = state;
      this.notify(state) //通知观察者
      }
      // 卸载观察者
      unSubscribe(observer) {
      this.observers = this.observers.filter(obs => obs !== observer)
      }
      //通知观察者
      notify(data) {
      this.observers.forEach(observer => observer.update(data))
      }
      }
      // 观察者类
      class Observer {
      constructor(name, subject) {
      this.name = name
      subject.addObserver(this)
      }
      update(data) {
      console.log(this.name + '修改后的状态'   + data)
      }
      }
      const subject = new Subject()
      const observer = new Observer('user', subject)
      subject.setState(2)
    • 发布订阅模式
      和观察者类似,但引入了 事件总线,发布者和订阅者解耦
      //实现event bus
      class EventBus {
      constructor() {
      this.events = {};
      }
      on(event, fn) {
      if (this.events[event]) {
      this.events[event].push(fn);
      } else {
      this.events[event] = [fn];
      }
      }
      emit(event, data) {
      this.events[event]?.forEach(item => item(data));
      }
      }
posted @ 2025-10-15 08:38  ycfenxi  阅读(3)  评论(0)    收藏  举报