zoukankan      html  css  js  c++  java
  • 模板模式

    模板模式:

    定义一个操作的骨架,但是一些步骤的实现放到子类中去。 模板方法使得子类不用重写或者改变某个操作的结构,只需要定义该操作的某些特定步骤。

    #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
    */
  • 相关阅读:
    算法总结--排序(快排未写)
    关于我,至目前的总结与展望
    二 python之数据类型和字符编码
    三 python之文件处理
    一 python编程基础
    markdown语法
    规模-复杂世界的简单法则---熵
    块级元素display:inline-block 在IE6 IE7无效
    CSS3 文本超出后显示省略号...
    让nodejs在iis上运行
  • 原文地址:https://www.cnblogs.com/hushpa/p/4432596.html
Copyright © 2011-2022 走看看