什么时候用到这种模式
1.有稳定的整体操作结构,各个步骤却有改变的需求
2.灵活的实现各个步骤的变换(步骤总是有实现的先后关系)
例子:
abstract class Cook {
public doCook() {
this.buyRawMaterial();
this.clearMaterial();
this.cooking();
this.outPot();
this.clearPot();
}
protected abstract buyRawMaterial(): void;
protected abstract clearMaterial();
protected abstract cooking(): void;
protected abstract outPot(): void;
protected clearPot(): void{
console.log('锅是一定要刷的');
}
}
class HuiGuoRou extends Cook {
protected buyRawMaterial() {
console.log('买肉');
}
protected clearMaterial() {
console.log('肉和辣椒洗干净');
}
protected cooking() {
console.log('很复杂');
}
protected outPot() {
console.log('好了要出锅的');
}
}
class TangChuPaiGu extends Cook {
protected buyRawMaterial() {
console.log('买排骨');
}
protected clearMaterial() {
console.log('排骨洗干净了');
}
protected cooking() {
console.log('很复杂,鬼知道怎么做的');
}
protected outPot() {
console.log('好了要出锅的');
}
}
class client {
test() {
console.log('今天吃啥');
let food: Cook = new HuiGuoRou();
food.doCook();
let food2: Cook = new TangChuPaiGu();
food2.doCook();
}
}
new client().test();