天天看點

C++模式(三)模闆方法模式

代碼示例如下:

#include <iostream>


using namespace std;

/* 抽象類 */
class AbstractClass
{
public:
    ~AbstractClass()
    {

    }
    AbstractClass()
    {

    }
    void TemplateMethod()
    {
        this->operator1();
        this->operator2();
    }

protected:
    virtual void operator1() = 0;
    virtual void operator2() = 0;

};

class ConcreteClass1:public AbstractClass
{
public:
    ConcreteClass1()
    {

    }
    ~ConcreteClass1();
protected:
    void operator1()
    {
        cout << "class1 operator1" << endl;
    }

    void operator2()
    {
        cout << "class1 operator2" << endl;
    }
};

class ConcreteClass2:public AbstractClass
{
public:
    ConcreteClass2()
    {

    }

    ~ConcreteClass2();

protected:
    void operator1()
    {
        cout << "class2 operator1" << endl;
    }

    void operator2()
    {
        cout << "class2 operator2" << endl;
    }
};




int main( void )
{
    AbstractClass* p1 = new ConcreteClass1();
    AbstractClass* p2 = new ConcreteClass2();

    p1->TemplateMethod();
    p2->TemplateMethod();

    return 0;
}