灏天阁

享元模式

· Yin灏
/**
 * 享元模式
 * 运用享元技术有效地支持大量的细粒度的对象,避免对象间拥有相同内容造成多余的开销。
 */
var FlyWeight = {
  moveX: function (x) {
    this.x = x;
  },
  moveY: function (y) {
    this.y = y;
  },
};

var Player = function (x, y, c) {
  this.x = x;
  this.y = y;
  this.color = x;
};
Player.prototype = FlyWeight;
Player.prototype.changeC = function (c) {
  this.color = c;
};

/**
 * 让精灵继承移动
 */
var Spirit = function (x, y, r) {
  this.x = x;
  this.y = y;
  this.r = r;
};
Spirit.prototype = FlyWeight;
Spirit.prototype.changeR = function (r) {
  this.r = r;
};

/**
 * 创建一个人
 */
var player1 = new Player(5, 6, "red");
console.log(player1); // Player { x: 5, y: 6, color: 'red', moveX: function, moveY: function }

/**
 * 让人移动起来
 */
player1.moveX(6);
player1.moveX(7);
player1.changeC("pink");
console.log(player1); // Player { x: 6, y: 7, color: 'pink', moveX: function, moveY: function }

/**
 * 创建一个精灵
 */
var spirit1 = new Spirit(2, 3, 4);
console.log(spirit1); // Spirit { x: 2, y: 3, r: 4, moveX: function, moveY: function }

/**
 * 让精灵移动起来
 */
spirit1.moveX(3);
spirit1.moveY(4);
spirit1.changeR(5); // Spirit { x: 3, y: 4, r: 5, moveX: function, moveY: function }

- Book Lists -