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

前端常用的几种设计模式

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

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

相关推荐
北城笑笑3 小时前
Vue 112 ,下篇:前端 dist 还原成 Vue3 + Vite 项目( krpano 全景接入与页面适配实战,Vue2 → Vue3 )
前端·javascript·vue.js·3d·前端框架·vue·webgl
我叫黑大帅4 小时前
搜“张三”把备注也带出来了?不用加高级筛选,如何让一个搜索框实现「选项直达」!
前端·javascript·面试
如夏倾城6 小时前
WAF (Web Application Firewall,Web应用防火墙)
前端·网络·安全·web安全·web app
图扑可视化7 小时前
基于图扑软件智慧制硅厂 Web SCADA 开发实践
前端·三维可视化·scada·hmi·组态软件
前端fighter7 小时前
2026年前端面试题总结(pdf版)
前端·pdf
谢小飞7 小时前
运维加了个参数,我们的网页挂掉了
前端·浏览器
CoderYanger8 小时前
Java EE 进阶:12.Spring AOP(第二弹)
java·前端·数据库·spring boot·spring·java-ee·mybatis
用户693717500138411 小时前
大模型蒸馏到底在蒸什么?一篇文章搞懂知识蒸馏概念
前端·后端·github
徐小夕11 小时前
实测 10 个前端 UI 生成开源 Skill|AI 输出直达上线标准
前端·vue.js·github
tong_li11 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(八):AI 知道这字哪课学的(SQLite 结构化查询入门)
前端·langchain