js设计模式11 享元模式

先来实验一下 js implements的威力
Function.prototype.implementsFor = function(parentClassOrObj){
  	if(parentClassOrObj.constructor === Function){
  		this.prototype = new parentClassOrObj;
  		this.prototype.parent = parentClassOrObj.prototype;
  		}else{
  			this.prototype = parentClassOrObj;
  			this.prototype.parent = parentClassOrObj;
  			}
  		this.prototype.constructor = this;
  		return this;
  	}

  /**
  function Interface(){
  	this.hehe = function(){alert("hehe");};
  	this.name = function(){alert("interface");};
  	this.size = 5;
  	}
  function Imple(){
  	this.haha = function(){alert("haha");};
  	this.name = function(){alert("imp");};
  	this.size = 6;
  	};
  Imple.implementsFor(Interface);
  var imp = new Imple();
  imp.hehe();
  imp.haha();
  imp.name();
  alert(imp.size);
  */
然后简单实现享元模式  不知道哪里写错 没跑出结果 晕死
var CoffeeOrder = {
  	serverCoffee:function(context){},
  	getFlavor:function(){}
  	}
  
  function CoffeeFlavor(newFlavor){
  	var flavor = newFlavor;
  	if(typeof(this.getFlavor) === "function"){
  		this.getFlavor = function(){
  			return flavor;
  			}
  		}
  	if(typeof(this.serverCoffee) === "function"){
  		this.serveCoffee = function(context){
  			alert(flavor + context.getTable());
  			}
  		}	
  	}
  CoffeeFlavor.implementsFor(CoffeeOrder);
  
  function CoffeeOrderContext(tableNumber){
  	var num = tableNumber;
  	return{
  		"getTable":function(){return num;}
  		}
  	}
  function CoffeeFlavorFactory(){
  	var flavors = [];
  	return{
  		"getCoffeeFlavor":function(flavorName){
  			var curFlavor = flavors[flavorName];
  			if(curFlavor === undefined){
  				curFlavor = new CoffeeFlavor(flavorName);
  				flavors.push([flavorName,curFlavor]);
  				}
  				return curFlavor;
  			},
  		"getTotalFlavorsMade":function(){
  			return flavors.length;
  			}
  		}
  	}
  
  //test
  var flavors = new CoffeeFlavor();
  var tables = new CoffeeOrderContext();
  var ordersMade = 0;
  var flavorFactory;
  function takeOrders(flavorName,table){
  	flavors[ordersMade] = flavorFactory.getCoffeeFlavor(flavorName);
  	tables[ordersMade++] = new CoffeeOrderContext(table);
  	}
  flavorFactory = new CoffeeFlavorFactory();
  takeOrders("Cappuccino", 2);
	takeOrders("Cappuccino", 2);
  takeOrders("Frappe", 1);
	takeOrders("Frappe", 1);
	takeOrders("Xpresso", 1);
	takeOrders("Frappe", 897);
  takeOrders("Cappuccino", 97);
	takeOrders("Cappuccino", 97);
  takeOrders("Frappe", 3);
  takeOrders("Xpresso", 3);
  takeOrders("Cappuccino", 3);
  takeOrders("Xpresso", 96);
  takeOrders("Frappe", 552);
  takeOrders("Cappuccino", 121);
  takeOrders("Xpresso", 121);

  for (var i = 0; i < ordersMade; ++i) {
      flavors[i].serveCoffee(tables[i]);
   }	
  alert("total obj made:"+flavorFactory.getTotalFlavorsMade());

你可能感兴趣的:(js,implements)