模板方法模式是类的行为模式.通过抽象类将部分逻辑以具体方法以及具体构造函数的形式实现,然后通过子类实现的抽象方法实现业务逻辑.不同的子类可以以不同的方式实现这些抽象方法.
① 抽象类:实现了模板方法,定义了算法的骨架.
② 具体类实现抽象类中的抽象方法,已完成完整的算法.
核心代码:
<pre><code>`class TemplateAnimation {
func showAnimation() { }
}
class CustomAnimation: TemplateAnimation {
override func showAnimation() {
print("FlyElephant--实现自定义动画")
}
}`</code></pre>
测试代码:
<pre><code>let animation:TemplateAnimation = CustomAnimation() animation.showAnimation()
</code></pre>
模板方式的优点:
① 模板方法模式通过把不变的行为搬移到超类,去除了子类中的重复代码.
② 子类负责抽象方法的具体实现.