zoukankan      html  css  js  c++  java
  • js 模板方法模式

    * 分离出共同点

    function Beverage() {}
    
    Beverage.prototype.boilWater = function() {
    	console.log("把水煮沸");
    }
    
    Beverage.prototype.brew = function() {
    	throw new Error('子类必须重写brew方法');
    }
    
    Beverage.prototype.pourInCup = function() {
    	throw new Error('子类必须重写pourInCup方法');
    }
    
    Beverage.prototype.addCondiments = function() {
    	throw new Error('子类必须重写addCondiments方法');
    }
    
    Beverage.prototype.init = function() {
    	this.boilWater();
    	this.brew();
    	this.pourInCup();
    	this.addCondiments();
    }
    
    function Coffee() {}
    
    Coffee.prototype = new Beverage();
    
    Coffee.prototype.brew = function() {
    	console.log("用沸水冲泡咖啡");
    }
    
    Coffee.prototype.pourInCup = function() {
    	console.log("把咖啡倒进杯子");
    }
    
    Coffee.prototype.addCondiments = function() {
    	console.log("加糖和牛奶");
    }
    
    var coffee = new Coffee();
    // coffee的原型Coffee没有init方法, 
    // 顺着原型链委托给父类的Beverage原型上的init方法
    coffee.init();
    
    console.log("-------------------------");
    
    function Tea() {}
    
    Tea.prototype = new Beverage();
    
    Tea.prototype.brew = function() {
    	console.log("用沸水浸泡茶叶");
    }
    
    Tea.prototype.pourInCup = function() {
    	console.log("把茶水倒进杯子");
    }
    
    Tea.prototype.addCondiments = function() {
    	console.log("加柠檬");
    }
    
    var tea = new Tea();
    tea.init();
    

      

      

  • 相关阅读:
    TreeList Linq
    MasterDetail Linq
    C# 事务处理
    设计模式——代理模式(Proxy Pattern)
    设计模式——装饰模式(Decorator Pattern)
    C# 调用WCF服务
    加密解密
    Effective C#高效编程(02:常量)
    切换城市功能
    DataPager控件使用
  • 原文地址:https://www.cnblogs.com/mingzhanghui/p/9303403.html
Copyright © 2011-2022 走看看