赞
踩
目录
模板方法模式:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
结构图如下(此图来自大话设计模式):
模板方法模式是通过把不变行为搬移到超类中,去除子类中的重复代码来提现他的优势。
模板方法模式提供了一个很好的代码复用。
当不变和可变的行为在方法的子类实现中混合在一起的时候,不变的行为就会在子类中重复出现。通过模板方法模式把这些行为搬移到单一的地方,这样就帮助子类摆脱重复不变行为的纠缠。
程序运行截图如下:
源码如下:
Head.h
- #ifndef HEAD_H
- #define HEAD_H
-
- class Fundamental{
-
- public:
- virtual void primitiveOperation1();
- virtual void primitiveOperation2();
-
- void templateMethod();
- virtual ~Fundamental();
- };
-
- class ConcreteClassA: public Fundamental{
-
- public:
- void primitiveOperation1();
- void primitiveOperation2();
-
- virtual ~ConcreteClassA();
- };
-
- class ConcreteClassB: public Fundamental{
-
- public:
- void primitiveOperation1();
- void primitiveOperation2();
-
- virtual ~ConcreteClassB();
- };
-
- #endif //HEAD_H
Head.cpp
- #include "Head.h"
- #include <iostream>
- #include <string>
- using namespace std;
-
- void Fundamental::primitiveOperation1()
- {
- cout << "Fundamental::primitiveOperation1()" << endl;
- }
-
- void Fundamental::primitiveOperation2()
- {
- cout << "Fundamental::primitiveOperation1()" << endl;
- }
-
- void Fundamental::templateMethod()
- {
- this->primitiveOperation1();
- this->primitiveOperation2();
- }
-
- Fundamental::~Fundamental()
- {
- cout << "Fundamental::~Fundamental()" << endl;
- }
-
- void ConcreteClassA::primitiveOperation1()
- {
- cout << "ConcreteClassA::primitiveOperation1()" << endl;
- }
-
- void ConcreteClassA::primitiveOperation2()
- {
- cout << "ConcreteClassA::primitiveOperation1()" << endl;
- }
-
- ConcreteClassA::~ConcreteClassA()
- {
- cout << "ConcreteClassA::~ConcreteClassA()" << endl;
- }
-
- void ConcreteClassB::primitiveOperation1()
- {
- cout << "ConcreteClassB::primitiveOperation1()" << endl;
- }
-
- void ConcreteClassB::primitiveOperation2()
- {
- cout << "ConcreteClassB::primitiveOperation2()" << endl;
- }
-
- ConcreteClassB::~ConcreteClassB()
- {
- cout << "ConcreteClassB::~ConcreteClassB()" << endl;
- }
main.cpp
- #include "Head.h"
- #include <iostream>
- #include <string>
- using namespace std;
-
-
- int main(int *argc, int *argv[]){
-
-
- Fundamental *fundamental = new ConcreteClassA;
-
- fundamental->templateMethod();
- delete fundamental;
-
- cout << "-------------- 华丽的分割线 --------------" << endl;
-
- Fundamental *concrete = new ConcreteClassB;
- concrete->templateMethod();
- delete concrete;
-
- getchar();
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。