模板模式:把具有特定步骤算法中的某些必要的处理委让给抽象方法,通过子类继承对抽象方法的不同实现改变整个算法的行为
Template Method 模式一般应用在具有以下条件的应用中:
- 具有统一的操作步骤或操作过程
- 具有不同的操作细节
- 存在多个具有同样操作步骤的应用场景,但某些具体的操作细节却各不相同
模板模式:在抽象类中统一操作步骤,并规定好接口;让子类实现接口。这样可以把各个具体的子类和操作步骤解耦合
class CreateCar {
public:
virtual void createHead() = 0;
virtual void createBody() = 0;
virtual void createTail() = 0;
public:
void createMethod() {
createHead();
createBody();
createTail();
}
};
class CreateBus :public CreateCar {
public:
void createHead(){
cout << "bus 组装 车头" << endl;
};
void createBody(){
cout << "bus 组装 车身" << endl;
};
void createTail(){
cout << "bus 组装 车尾" << endl;
};
};
class CreateJeep :public CreateCar {
public:
void createHead() {
cout << "jeep 组装 车头" << endl;
};
void createBody() {
cout << "jeep 组装 车身" << endl;
};
void createTail() {
cout << "jeep 组装 车尾" << endl;
};
};
int main()
{
CreateBus* bus = new CreateBus;
//bus->makeHead();
//bus->makeBody();
//bus->makeTail();
bus->createMethod();
CreateJeep* jeep = new CreateJeep;
//jeep->makeHead();
//jeep->makeBody();
//jeep->makeTail();
jeep->createMethod();
delete bus;
delete jeep;
system("pause");
return 0;
}