享元模式 - Flyweight

90 阅读1分钟

一、定义

一种用于性能优化的模式,它的目标是尽量减少共享对象的数量。

二、核心

运用共享技术来有效支持大量细粒度的对象。
强调将对象的属性划分为内部状态(属性)与外部状态(属性)。内部状态用于对象的共享,通常不变;而外部状态则剥离开来,由具体的场景决定。

三、实现

// 共享部分
const FlyWeight = {
  moveX: function(x) {
      this.x = x;
  },
  moveY: function(y) {
      this.y = y;
  }
}
// 玩家
const Player = function(x, y, color) {
  this.x = x;
  this.y = y;
  this.color = color;
}
Player.prototype = FlyWeight

// 怪兽
const Monster = function() {
  this.x = 10;
  this.y = 30;
  this.call = '嗷嗷~';
  this.name = '哥斯拉';
}
Monster.prototype = FlyWeight;

// 测试
const player = new Player(30, 10, '#333')
player.moveX(5); player.moveY(-10)

const monster = new Monster()
monster.moveY(-4); monster.moveY(10)

console.log(player) // ==> { x: 5, y: -10, color: '#333' }
console.log(monster) // ==> { x: 10, y: 10, call: '嗷嗷~', name: '哥斯拉' }

四、小结

享元模式把共有的数据和方法提取出来,目的是为了提高程序的执行效率,减少内存消耗,进一步提升系统的性能。

跳转:设计模式目录