设计模式之模板方法模式(Template Pattern)

概述

The Template pattern defines a structure for sub classes in which steps of an algorithm and their order are defined. This ensures that the sub classes follow the exact same steps, providing better overview and consistency. It also allows to define default implementations for steps that can be overridden by subclasses.

模板方法模式就是给定一个算法的步骤,但是具体算法实现交给子类完成。还是比较好理解的。

本文类图

Template本文类图

代码示例

BaseSteps的templateMethod就是模板方法,他定义了具体的算法步骤。

BaseSteps的templateMethod就是模板方法

ConcreA是BaseSteps中算法的具体实现。

ConcreA

ConcreB是BaseSteps中算法的具体实现。

ConcreB

测试结果

TemplateMethod的测试结果

参考资料

参考代码资料推荐看这篇文章本文代码GitHub地址

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。