Skip to content
本文总阅读量

模版方法模式

JS

JS
// 抽象类
var  AB  =  function  ()  {  }
AB.prototype.boilWater  =  function  ()  {
    console.log('把水煮沸')
}


AB.prototype.brew  =  function  ()  {
    throw  new  Error('子类必须重写 brew 方法');
}


AB.prototype.pourInCup  =  function  ()  {
    throw  new  Error('子类必须重写 pourInCup 方法');
}


AB.prototype.addCondiments  =  function  ()  {
    throw  new  Error('子类必须重写 addCondiments 方法');
}


AB.prototype.CC  =  function  ()  {
    return  true
}


AB.prototype.init  =  function  ()  {
    this.boilWater()
    this.brew()
    this.pourInCup()
    if  (this.CC())  {
        this.addCondiments()
    }
}
  
 
var  Tea  =  function  ()  {  }


Tea.prototype  =  new  AB()


Tea.prototype.brew  =  function  ()  {
    console.log('用沸水冲泡咖啡');
};


Tea.prototype.pourInCup  =  function  ()  {
    console.log('把咖啡倒进杯子');
};  


Tea.prototype.init()

输出

  • 把水煮沸
  • 用沸水冲咖啡
  • 把咖啡倒进杯子
  • Uncaught Error: 子类必须重写addCondiments方法