C++设计模式之模板模式

       在GOF的《设计模式:可复用面向对象软件的基础》一书中对模板方法模式是这样说的:定义一个操作中的算法骨架,而将一些步骤延迟到子类中。TemplateMethod使得子类可以不改变一个算法的接口即可重定义改算法的某些特定步骤。模板方法简单来说就是在基类中定义一个算法模型,该模型又包含多个算法部分,而各个算法的实现不是在该基类中完成,而是通过继承类对该算法的重定义函数实现,从而实现不同的算法。

                                                                                       UML类图

                                                              

       例如在具体的实例中,mybasicclass基类中有个TemplateMethod()方法,该方法定义了一个算法模型,在该算法中调用了OneOperation()和TwoOperation()两个成员方法,也可将其视为算法的接口,这些成员方法组成了整个算法的各个部分。这些成员方法则可以根据子类的不同而实现不同的改变。模板方法模式提供了一个很好的代码复用方法。

#ifndef MYBASICCLASS_H
#define MYBASICCLASS_H

#include <iostream>
using namespace std;
//抽象基类 实现一个模板的方法
class mybasicclass
{
public:
   virtual~mybasicclass()
    {

    }

    //模板方法 ,只在抽象基类中实现
    void TemplateMethod()
    {
        cout<<"OneOperation"<<endl;
        this->OneOperation();
        cout<<"TwoOperation"<<endl;
        this->TwoOperation();
    }
protected:
    virtual void OneOperation() = 0;
    virtual void TwoOperation() = 0;

    mybasicclass()
    {

    }

};

class ConsonclassOne:public mybasicclass
{
public:
    ConsonclassOne()
    {

 }
   ~ConsonclassOne()
 {

 }
protected:
     void OneOperation()
{
    cout<<"ConcreteClassOne...PrimitiveOperationOne"<<endl;
}
     void TwoOperation()
{
    cout<<"ConcreteClassOne...PrimitiveOperationTwo"<<endl;
}
};

class ConsonclassTwo:public mybasicclass
{
public:
    ConsonclassTwo()
 {

 }
   ~ConsonclassTwo()
 {

 }
protected:
     void OneOperation()
{
    cout<<"ConcreteClassTwo...PrimitiveOperationOne"<<endl;
}
     void TwoOperation()
{
    cout<<"ConcreteClassTwo...PrimitiveOperationTwo"<<endl;
}
};

#endif // MYBASICCLASS_H
#include <iostream>
#include "mybasicclass.h"

using namespace std;

int main()
{
    mybasicclass * p1 =new ConsonclassOne();
    mybasicclass * p2 = new ConsonclassTwo();

    p1->TemplateMethod();
    p2->TemplateMethod();
    cout << "Hello World!" << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值