博客
关于我
设计模式之模板模式
阅读量:358 次
发布时间:2019-03-04

本文共 1297 字,大约阅读时间需要 4 分钟。

目录


模板模式template

概念

  • Template Method模式也叫模板方法模式,是行为模式之一,它把具有特定步骤算法中的某些必要的处理委让给抽象方法,通过子类继承对抽象方法的不同实现改变整个算法的行为。

应用场景

  • Template Method模式一般应用在具有以下条件的应用中:
    • 具有统一的操作步骤或操作过程
    • 具有不同的操作细节
    • 存在多个具有同样操作步骤的应用场景,但某些具体的操作细节却各不相同

总结

  • 在抽象类中统一操作步骤,并规定好接口
  • 子类实现接口。这样可以把各个具体的子类和操作步骤接耦合

角色和职责

  • AbstractClass:
    • 抽象类的父类
  • ConcreteClass:
    • 具体的实现子类
  • templateMethod():
    • 模板方法
  • method1()与method2():
    • 具体步骤方法  
       

案例

#include 
using namespace std;class MakeCar{public: virtual void makeHead() = 0; virtual void makeBody() = 0; virtual void makeTail() = 0;public: //把一组行为 变成 一个模板 void make() { makeHead(); makeBody(); makeTail(); }};class MakeBus : public MakeCar{public: virtual void makeHead() { cout << "bus 组装 车头" << endl; } virtual void makeBody() { cout << "bus 组装 车身" << endl; } virtual void makeTail() { cout << "bus 组装 车尾" << endl; }};class MakeJeep : public MakeCar{public: virtual void makeHead() { cout << "Jeep 组装 车头" << endl; } virtual void makeBody() { cout << "Jeep 组装 车身" << endl; } virtual void makeTail() { cout << "Jeep 组装 车尾" << endl; }};void main(){ MakeCar *bus = new MakeBus; //bus->makeHead(); //bus->makeBody(); //bus->makeTail(); bus->make(); MakeCar *jeep = new MakeJeep; //jeep->makeHead(); //jeep->makeBody(); //jeep->makeTail(); jeep->make(); delete bus; delete jeep; cout<<"hello..."<

【注】参考传智扫地僧C++设计模式

转载地址:http://taur.baihongyu.com/

你可能感兴趣的文章
Nginx服务器的安装
查看>>
Nginx标准配置文件(包括反向代理、大文件上传、Https证书配置、文件预览等)
查看>>
Nginx模块 ngx_http_limit_conn_module 限制连接数
查看>>
Nginx模块 ngx_http_limit_req_module 限制请求速率
查看>>
nginx添加允许跨域header头
查看>>
nginx添加模块与https支持
查看>>
nginx状态监控
查看>>
Nginx用户认证
查看>>
Nginx的location匹配规则的关键问题详解
查看>>
Nginx的Rewrite正则表达式,匹配非某单词
查看>>
Nginx的使用总结(一)
查看>>
Nginx的使用总结(三)
查看>>
Nginx的使用总结(二)
查看>>
Nginx的使用总结(四)
查看>>
Nginx的可视化神器nginx-gui的下载配置和使用
查看>>
nginx的平滑升级方法:
查看>>
Nginx的是什么?干什么用的?
查看>>
Nginx的端口修改问题
查看>>
nginx看这一篇文章就够了
查看>>
Nginx知识详解(理论+实战更易懂)
查看>>