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

前端常用的几种设计模式

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

模块模式(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 框架和库的工作原理是非常有帮助的。

相关推荐
難釋懷31 分钟前
Vue解决开发环境 Ajax 跨域问题
前端·vue.js·ajax
特立独行的猫a35 分钟前
Nuxt.js 中的路由配置详解
开发语言·前端·javascript·路由·nuxt·nuxtjs
咸虾米38 分钟前
在uniCloud云对象中定义dbJQL的便捷方法
前端·javascript
梨子同志39 分钟前
JavaScript Proxy 和 Reflect
前端·javascript
汤圆炒橘子43 分钟前
状态策略模式的优势分析
前端
90后的晨仔1 小时前
解析鸿蒙 ArkTS 中的 Union 类型与 TypeAliases类型
前端·harmonyos
IT_陈寒1 小时前
Element Plus 2.10.0 重磅发布!新增Splitter组件
前端·人工智能·后端
挑战者6668881 小时前
vue入门环境搭建及demo运行
前端·javascript·vue.js
贩卖纯净水.1 小时前
Webpack的基本使用 - babel
前端·webpack·node.js
用户882093216672 小时前
Vue组件通信全攻略:从父子传参到全局状态管理,一篇搞定!
前端