Template Method - 模板方法模式

來源:互聯網
上載者:User

標籤:

目的定義一個操作中的算的骨架,將一些步驟的具體實現延遲到子類中,模板方法模式使得子類可以不改變一個演算法的結構就可以重新定義該演算法的某些特定步驟。
案例一個含有Application和Document類的應用程式框架,Application類負責開啟一個外部文檔,當文檔中的內容讀入之後,就用Document來表示。在Application中存在方法openDocument進行文檔的操作:
 
  1. void Application::openDocument(const char* name)
  2. {
  3. if(!canOpenDocument(name))
  4. return;
  5. Document* doc = createDocument();
  6. if(doc != NULL)
  7. {
  8. m_docs->addDocument(doc);
  9. aboutToOpenDocument(doc);
  10. doc->open();
  11. doc->read();
  12. }
  13. }
在Application的openDocument中定義了開啟一個文檔的每一個主要步驟,它檢查了文檔是否能被開啟,並建立與應用相關的Document對象,並且從檔案中讀入該Document,此時openDocument就是 模板方法。一個模版方法用一些抽象的操作定義一個演算法,而子類將重定義這些操作以提供具體的行為:

類Application提供需要子類重定義的操作:
 
  1. class Application
  2. {
  3. public:
  4. void openDocument(const char* name);
  5. protected:
  6. virtual void canOpenDocument(const char* name);
  7. virtual void createDocument();
  8. virtual void aboutToOpenDocument();
  9. private:
  10. vector<Document*> m_docs;
  11. };
MyApplication自需要是實現自己需要重定義的操作:
 
  1. class MyApplication : public Application
  2. {
  3. protected:
  4. virtual Document* createDocument();
  5. virtual void aboutToOpenDocument();
  6. };
  7. Document* MyApplication::createDocument()
  8. {
  9. return new MyDocument();
  10. }
  11. void aboutToOpenDocument()
  12. {
  13. // initialize doc object.
  14. }
Document和MyDocument也是類似的實現。
適用性
  • 一次性定義一個演算法的不變的部分,將可變的行為留給子類來實現。
  • 各子類中公用的行為應該提取出來,並集中到一個公用父類中以避免代碼重複。
  • 控制子類擴充。

Template Method - 模板方法模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.