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

前端常用的几种设计模式

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

模块模式(Module Pattern):

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

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 中,事件处理机制就是观察者模式的一个典型例子。

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,就利用了这种模式来管理状态。

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 的对象创建和继承中起着重要的作用。

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):

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

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 中得到了应用。

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):

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

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

你可能感兴趣的:(前端,设计模式,观察者模式)