现在的位置: 首页 > 综合 > 正文

模板模式(C++)

2012年10月29日 ⁄ 综合 ⁄ 共 718字 ⁄ 字号 评论关闭
#include <iostream>
using namespace std;

class Road
{
public:
    Road(){}
    virtual ~Road(){}
    void operation()
    {
        start();
        step1();
        step2();
        step3();
        end();
    }
    void start(){cout<<"start"<<endl;}
    void end(){cout<<"end"<<endl;}
    virtual void step1()=0;
    virtual void step2()=0;
    virtual void step3()=0;
};

class way1 : public Road
{
public:
    way1(){}
    virtual ~way1(){}
    void step1(){cout<<"way1_step1"<<endl;}
    void step2(){cout<<"way1_step2"<<endl;}
    void step3(){cout<<"way1_step3"<<endl;}
};

class way2 : public Road
{
public:
    way2(){}
    virtual ~way2(){}
    void step1(){cout<<"way2_step1"<<endl;}
    void step2(){cout<<"way2_step2"<<endl;}
    void step3(){cout<<"way2_step3"<<endl;}
};

int main()
{
    Road *pr1=new way1;
    Road *pr2=new way2;

    pr1->operation();
    pr2->operation();

    delete pr2;
    delete pr1;

    system("pause");
    return 0;
}

抱歉!评论已关闭.