模版方法是指在父类搭建算法框架,通过子类继承这些算法框架,并调用父类的模版方法对算法框架进行调用,特别是解决众多类具有很多相同算法,只有少量不同的场景
例如泡茶与泡咖啡都有很多相同的流程,只是细节有些差异,就可以通过模版方法进行归纳
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| abstract class Behavior{ abstract BoilWater():void;
abstract AddRawMaterials():void;
abstract AddSeasoning():void; abstract WaitTimer():void;
init(){ this.BoilWater(); this.AddRawMaterials(); this.AddSeasoning(); this.WaitTimer(); } }
class Coffe extends Behavior{ BoilWater(){ console.log('加入水'); } AddRawMaterials(){ console.log('加咖啡'); } AddSeasoning(){ console.log('加奶精'); } WaitTimer(){ console.log('等待4分钟'); } }
class Tea extends Behavior{ BoilWater(){ console.log('加入水'); } AddRawMaterials(){ console.log('加茶'); } AddSeasoning(){ console.log('不加'); } WaitTimer(){ console.log('等待4分钟'); } }
let coffe = new Coffe(); coffe.init();
let tea = new Tea(); tea.init();
|