时间:2020-11-04 11:05:13 | 栏目:C代码 | 点击:次
模板方法模式使用继承来实现模式的功能,在基类使用一个方法来定义算法的各个步骤,这些步骤(方法)的具体实现会放到子类中,通过这样来实现不同算法对象的算法拼合,完成该对象整体算法的实现。
作用
模板方法中定义了具体操作中所使用算法的各个步骤,并将其实现交由子类完成,从而实现多种不同的功能;
类视图
实现
class Lunch { public: Lunch(){} virtual ~Lunch(){} void feed() { cooking(); eating(); cleaning(); } virtual void cooking()=0; virtual void eating() { cout<<"I am eating,Please don't disturb me\n"; } virtual void cleaning(); }; class MCMeal : public Lunch { public: MCMeal(){} virtual ~MCMeal(){} void cooking() { cout<< "I am cooking Mc Meal\n"; } void cleaning() { cout<< "I am cleaning Mc plates"; } }; class KFCMeal : public Lunch { public: KFCMeal() {} virtual ~KFCMeal(){} void cooking() { cout<< "I am cooking KFC Meal\n"; } void eating { cout<< "KFC Meal is good\n"; } void cleaning() { cout<< "I am cleaning KFC plates and cups\n"; } }; int main() { Lunch* meal1 = new McMeal(); meal1.feed(); Lunch* meal2 = new KFCMeal(); meal2.feed(); }
应用场景