标签:
模板模式:
定义一个操作的骨架,但是一些步骤的实现放到子类中去。 模板方法使得子类不用重写或者改变某个操作的结构,只需要定义该操作的某些特定步骤。
#include <iostream> using namespace std; /* 模板类,由模板方法来控制整体逻辑,子方法由子类实现 */ class AbstractPage { public: virtual void getInfo() = 0; virtual void createView() = 0; void drawPage(); //this is template method to control the logic }; void AbstractPage::drawPage() { cout<<"First step"<<endl; getInfo(); cout<<"Second step"<<endl; createView(); } /* 子类,实现具体方法 */ class PageA: public AbstractPage { public: void getInfo(); void createView(); }; void PageA::getInfo() { cout<<"Get page A‘s info"<<endl; } void PageA::createView() { cout<<"create page A‘s view with the info"<<endl; } class PageB: public AbstractPage { public: void getInfo(); void createView(); }; void PageB::getInfo() { cout<<"Get page B‘s info"<<endl; } void PageB::createView() { cout<<"create page B‘s view with the info"<<endl; } /* 测试 */ void main() { AbstractPage *pageA = new PageA(); pageA->drawPage(); cout<<endl; AbstractPage *pageB = new PageB(); pageB->drawPage(); delete pageA; delete pageB; system("pause"); } /* Result First step Get page A‘s info Second step create page A‘s view with the info First step Get page B‘s info Second step create page B‘s view with the info */
标签:
原文地址:http://www.cnblogs.com/hushpa/p/4432596.html