前端常用的几种设计模式--观察者模式、单例模式等

前端常用的几种设计模式

前端开发中有几种设计模式被广泛使用,对于开发者来说,理解和掌握这些模式能够帮助他们写出更加清晰、可维护的代码。以下是一些前端开发中常用的设计模式:

模块模式(Module Pattern):

这种模式被广泛应用在 JavaScript 中,用来创建模块,这些模块可以有私有和公有的方法和变量。这种模式有助于减少全局作用域的污染,提高代码的可维护性。

bash 复制代码
var myModule = (function() {
  var privateVar = 'I am private...';
  function privateMethod() {
    console.log(privateVar);
  }
  return {
    publicMethod: function() {
      privateMethod();
    }
  };
})();
myModule.publicMethod(); // Outputs: 'I am private...'

观察者模式(Observer Pattern):

也被称为发布/订阅模式,这种模式允许对象订阅另一对象的特定活动并在适当的时候被通知。在 JavaScript 中,事件处理机制就是观察者模式的一个典型例子。

bash 复制代码
class Observable {
  constructor() {
    this.observers = [];
  }
  subscribe(observer) {
    this.observers.push(observer);
  }
  notify(data) {
    this.observers.forEach(observer => observer(data));
  }
}

const obs = new Observable();
obs.subscribe(data => console.log(data));
obs.notify('Hello!'); // Outputs: 'Hello!'

中介者模式(Mediator Pattern):

这种模式通过引入一个中介者对象来简化对象之间的通信。这对于处理复杂的交互系统非常有用,比如 GUI。在前端框架中,比如 Redux 和 Vuex,就利用了这种模式来管理状态。

bash 复制代码
class Mediator {
  constructor() {
    this.channels = {};
  }
  subscribe(channel, callback) {
    if (!this.channels[channel]) {
      this.channels[channel] = [];
    }
    this.channels[channel].push(callback);
  }
  publish(channel, data) {
    if (!this.channels[channel]) return;
    this.channels[channel].forEach(callback => callback(data));
  }
}

const mediator = new Mediator();
mediator.subscribe('event', data => console.log(data));
mediator.publish('event', 'Hello!'); // Outputs: 'Hello!'

原型模式(Prototype Pattern):

这是 JavaScript 的核心模式,由于 JavaScript 是基于原型的,所以它在 JavaScript 的对象创建和继承中起着重要的作用。

bash 复制代码
function Person() {
}
Person.prototype.name = 'John';
Person.prototype.sayHello = function() {
  console.log('Hello ' + this.name);
}

const person1 = new Person();
person1.sayHello(); // Outputs: 'Hello John'

工厂模式(Factory Pattern):

这种模式用于创建对象,它提供了一个通用的接口来创建对象,可以在运行时根据需要决定实例化哪个类。

bash 复制代码
function CarMaker() { }
CarMaker.prototype.drive = function () {
  return `Vroom, I have ${this.doors} doors`;
};
CarMaker.factory = function (type) {
  let constructor = type,
    newCar;
  if (typeof CarMaker[constructor] !== 'function') {
    throw {
      name: 'Error',
      message: constructor + ' doesn't exist'
    };
  }
  if (typeof CarMaker[constructor].prototype.drive !== 'function') {
    CarMaker[constructor].prototype = new CarMaker();
  }
  newCar = new CarMaker[constructor]();
  return newCar;
};

CarMaker.Compact = function () {
  this.doors = 4;
};
CarMaker.Convertible = function () {
  this.doors = 2;
};
CarMaker.SUV = function () {
  this.doors = 24;
};

const corolla = CarMaker.factory('Compact');
const solstice = CarMaker.factory('Convertible');
const cherokee = CarMaker.factory('SUV');
console.log(corolla.drive()); // "Vroom, I have 4 doors"
console.log(solstice.drive()); // "Vroom, I have 2 doors"
console.log(cherokee.drive()); // "Vroom, I have 24 doors"

装饰者模式(Decorator Pattern):

这种模式允许在运行时动态地为对象添加新的行为。在 ES7 中,装饰者已经成为了一个提案,并在一些前端框架,如 Angular 和 Ember 中得到了应用。

bash 复制代码
function Book(title, author, price) {
  this.title = title;
  this.author = author;
  this.price = price;
}
Book.prototype.getPrice = function() {
  return this.price;
};

function DecoratedBook(book, discount) {
  this.book = book;
  this.discount = discount;
}
DecoratedBook.prototype.getPrice = function() {
  return this.book.getPrice() * (1 - this.discount);
};

const book = new Book('JavaScript: The Good Parts', 'Douglas Crockford', 39);
const discountedBook = new DecoratedBook(book, 0.1);
console.log(discountedBook.getPrice()); // Outputs: 35.1

单例模式(Singleton Pattern):

这种模式限制一个类只能有一个实例,并提供一个全局的访问点。在前端开发中,这种模式常用于创建全局的配置对象。

bash 复制代码
var Singleton = (function() {
  var instance;
  function createInstance() {
    return new Object('I am the instance');
  }
  return {
    getInstance: function() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // Outputs: true

以上这些模式并不是前端开发者必须要记住的,但对于写出高质量代码以及理解现代 JavaScript 框架和库的工作原理是非常有帮助的。

相关推荐
深念Y13 分钟前
Lenovo XiaoXinAir 14 — 性能模式切换
前端·网络
码匠许师傅18 分钟前
【设计模式精讲】14.外观模式(Facade)
c++·设计模式·uml·外观模式
计算机魔术师34 分钟前
Meta突然杀进第一梯队:一个新模型,把AI推理成本打下来8倍
前端
IT_陈寒1 小时前
Redis缓存雪崩把我坑惨了,这次长记性了
前端·人工智能·后端
风骏时光牛马1 小时前
提示词工程:大模型效能挖掘与指令设计实战
前端
仓三1 小时前
Chrome DevTools MCP 上手:让 Coding Agent 自己调试前端页面
前端·chrome devtools·mcp
计算机魔术师1 小时前
扒完Google AI Agent挑战赛的前三名,我发现了一个共同点
前端
不可能片场1 小时前
resources/app 为何能覆盖 app.asar
前端·electron
小婉1 小时前
我用 Next.js + React Flow 从零搭建了一个可视化 AI 工作流编排平台
前端·人工智能·node.js
skiyee2 小时前
🚀 用 17 行代码给 UniApp 加上全局登录拦截
前端·uni-app