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

前端常用的几种设计模式

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

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

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. MVC模式(Model-View-Controller) MVC模式是一种将应用程序分成三个核心部分的设计模式,分别是模型(Model)、视图(View)和控制器(Controller)。模型负责处理数据和业务逻辑,视图负责界面展示,控制器协调模型和视图之间的交互。 2. MVVM模式(Model-View-ViewModel) MVVM模式是一种基于MVC模式的设计模式,它将视图和模型之间的通信通过一个名为ViewModel的中间件实现。ViewModel负责处理视图和模型之间的数据绑定和事件处理,实现了视图和模型的解耦。 3. 单例模式(Singleton) 单例模式是一种创建型模式,它保证一个类只有一个实例,并提供全局访问点。这种模式在需要全局共享资源的情况下非常有用,比如数据库连接池、线程池等。 4. 观察者模式(Observer) 观察者模式是一种行为模式,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,当主题对象状态发生改变时,它的所有观察者都会收到通知并更新自己的状态。 5. 策略模式(Strategy) 策略模式是一种行为模式,它定义了一系列算法,将每个算法都封装起来,使它们可以相互替换。这样,客户端可以在不改变代码的情况下选择不同的算法,从而实现不同的行为。 6. 工厂模式(Factory) 工厂模式是一种创建型模式,它定义了一个用于创建对象的接口,但是由子类决定要实例化的类是哪一个。这样,工厂方法让类的实例化推迟到了子类中进行,从而实现了解耦和灵活性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

临夏_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值