博客
关于我
设计模式之模板模式
阅读量: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负载均衡
查看>>
Nginx负载均衡和F5的区别---系统运维工作笔记001
查看>>
nginx负载均衡和反相代理的配置
查看>>
nginx负载均衡器处理session共享的几种方法(转)
查看>>
nginx负载均衡的5种策略
查看>>
nginx负载均衡的5种策略(转载)
查看>>
nginx负载均衡的五种算法
查看>>
Nginx负载均衡(upstream)
查看>>
nginx转发端口时与导致websocket不生效
查看>>
Nginx运维与实战(二)-Https配置
查看>>
Nginx部署_mysql代理_redis代理_phoenix代理_xxljob代理_websocket代理_Nacos代理_内网穿透代理_多系统转发---记录021_大数据工作笔记0181
查看>>
Nginx配置HTTPS服务
查看>>
Nginx配置Https证书
查看>>
Nginx配置http跳转https
查看>>
Nginx配置ssl实现https
查看>>
Nginx配置TCP代理指南
查看>>
NGINX配置TCP连接双向SSL
查看>>
Nginx配置——不记录指定文件类型日志
查看>>
nginx配置一、二级域名、多域名对应(api接口、前端网站、后台管理网站)
查看>>