设计模式之模板方法模式(Template Method Pattern)

  定义:定义一个操作中的算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

  优点:1、封装不变部分(在父类实现),扩展可变部分(在子类实现)

     2、提取公共部分代码,便于维护

       3、行为由父类控制,子类实现

  缺点:按照我们的设计习惯,抽象类负责声明最抽象、最一般的事物属性和方法,实现类完成具体的事物属性和方法,但模板类却颠倒了,抽象类却定义了部分抽象方法,由子类实现,子类执行的结果影响了父类的结果,也就是子类对父类产生了影响,这在复杂的项目中会带来代码阅读的困难。

using namespace std;
class course
{
public:
    course() {}
    ~course() {}
    virtual void beginCourse() = 0;
    virtual void operPage() = 0;
    virtual void endCourse() = 0;

    void begin() 
    {
        this->beginCourse();
        this->operPage();
        this->endCourse();
    }

};

//课程:《操作系统》
class OperatingSystem : public course
{
public:
    OperatingSystem() {}
    ~OperatingSystem() {}
    void beginCourse() 
    {
        printf("操作系统课程开始了!\n");
    }
    void operPage() 
    {
        printf("课本翻到101页!\n");
    }

    void endCourse() 
    {
        printf("下课去吃饭!\n\n");
    }
};

//课程:《计算机网络》
class ComputerNetwork : public course
{
public:
    ComputerNetwork() {}
    ~ComputerNetwork() {}
    void beginCourse()
    {
        printf("计算机网络课程开始了!\n");
    }
    void operPage()
    {
        printf("课本翻到108页!\n");
    }

    void endCourse()
    {
        printf("下课去图书馆!\n");
    }
};
int main()
{
    OperatingSystem OS;
    OS.begin();

    ComputerNetwork CN;
    CN.begin();
}

posted @ 2017-03-21 15:47  Forever-Road  阅读(145)  评论(0编辑  收藏  举报