在有些情况下,一个功能在基础功能上是不会变的,算法的基本骨架也是确定的,但是在某些场景下算法的具体实现有些差异。应对这种问题,可以采用模板方法模式:
abstract class Salary{ abstract ComputeBaseSalary():void; abstract ComputeDecuteSalary():void; abstract ComputeBonusSalary():void; //定义了通用实现与算法骨架,具体实现在子类中有差别 ComputeSalary():void{ console.log("开始计算工资"); this.ComputeBaseSalary(); this.ComputeDecuteSalary(); this.ComputeBonusSalary(); } } class ITSalary extends Salary{ ComputeBaseSalary():void{ console.log("IT基本工资"); } ComputeDecuteSalary():void{ console.log("IT没有提成"); } ComputeBonusSalary():void{ console.log("IT奖金"); } } class SalesSalary extends Salary{ ComputeBaseSalary():void{ console.log("Sales基本工资"); } ComputeDecuteSalary():void{ console.log("Sales提成"); } ComputeBonusSalary():void{ console.log("Sales没有奖金"); } } var itsalary=new ITSalary(); itsalary.ComputeSalary(); var salessalary=new SalesSalary();
salessalary.ComputeSalary();
欢迎加入QQ群讨论:573336726