ruk·si

🍦 JavaScript Pattern
Flyweight

Updated at 2015-05-13 16:08
var MenuItem = (function() {
  var MenuItem = function(name) {
    this.name = name;
  };
  MenuItem.prototype.getName = function() {
    return this.name;
  };
  MenuItem.prototype.serve = function() {
    return 'Serving ' + this.name;
  };
  return MenuItem;
}());

var MenuItemFactory = (function() {
  var MenuItemFactory = function() {
    this.menuItems = {};
  };
  MenuItemFactory.prototype.getMenuItem = function(name) {
    var item = this.menuItems[name];
    if (item === undefined) {
      item = new MenuItem(name);
      this.menuItems[name] = item;
    }
    return item;
  };
  MenuItemFactory.prototype.getSeparateObjectCount = function() {
    var asArray = [];
    for (var item in this.menuItems) {
      if (Object.prototype.hasOwnProperty.call(this.menuItems, item)) {
        asArray.push(item);
      }
    }
    return asArray.length;
  };
  return MenuItemFactory;
}());

var Diner = (function() {
  var Diner = function() {
    this.ordersTaken = [];
    this.menuItemFactory = new MenuItemFactory();
  };
  Diner.prototype.takeOrder = function(orderName) {
    this.ordersTaken.push(this.menuItemFactory.getMenuItem(orderName));
  };
  Diner.prototype.serveAll = function() {
    for (var i = 0; i < this.ordersTaken.length; ++i) {
      this.ordersTaken[i].serve();
    }
  };
  Diner.prototype.getOrdersTakenCount = function() {
    return this.ordersTaken.length;
  };
  Diner.prototype.getMenuItemCount = function() {
    return this.menuItemFactory.getSeparateObjectCount()
  };
  return Diner;
}());

var diner = new Diner();
diner.takeOrder('Coffee');
diner.takeOrder('Coffee');
diner.takeOrder('Bacon and Eggs');
diner.takeOrder('Bacon and Eggs');
diner.takeOrder('Waffles');
diner.takeOrder('Bacon and Eggs');
diner.takeOrder('Coffee');
diner.takeOrder('Coffee');
diner.takeOrder('Bacon and Eggs');
diner.takeOrder('Waffles');
diner.takeOrder('Coffee');
diner.takeOrder('Waffles');
diner.takeOrder('Bacon and Eggs');
diner.takeOrder('Coffee');
diner.takeOrder('Waffles');
diner.serveAll();
console.assert(diner.getOrdersTakenCount() === 15);
console.assert(diner.getMenuItemCount() === 3);