首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

【设计形式】之模板方法(Template Method)

2012-08-10 
【设计模式】之模板方法(Template Method)模板方法的定义为:再一个操作中定义一个算法的骨架,将算法中的一些

【设计模式】之模板方法(Template Method)

模板方法的定义为:再一个操作中定义一个算法的骨架,将算法中的一些步骤延迟到子类去实现。模板方法允许子类在不该变算法结构的情况下重新定义算法的某些步骤。

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclassesredefine certain steps of an algorithm without changing the algorithm's structure.

在实际的面向对象设计中,模板方法的使用应该是非常广泛的。

模板方法一个很重要的作用,就是提高代码复用性,避免代码冗余。如果出现重复代码,就应该考虑是不是设计出错了。(When we got code duplication, that's a good sign we need to clean up the design)。

模板方法,顾名思义就是一个方法(method),在这个方法内部定义了一个算法的模板,算法的结构是不会变化的,算法中不变的部分会在模板方法所在的类中封装,依赖于具体实现的部分则在其他地方定义。

模板方法符合Holleywood Principle,即 "Don't call us, we'll call you“。




当然,模板方法的实现并非都是通过的继承的方式实现。

以下例子便是再模板方法中调用了其他类的方法。

public class Duck implements Comparable {    String name;    int weight;    public Duck(String name, int weight) {        this.name = name;        this.weight = weight;    }    public String toString() {        return name + " weights " + weight;    }    @Override    public int compareTo(Object object) {        Duck otherDuck = (Duck)object;        if (this.weight < otherDuck.weight) {            return -1;        } else if (this.weight == otherDuck.weight) {            return 0;        } else { // this.weight > otherDuck.weight            return 1;        }    }}

模板方法模式与策略模式有相似点,他们都封装了一个算法,但是模板放发只是抽象了算法的一部分,而策略模式抽象的是整个算法,而且策略模式是同哦那天过组合(Composition)实现,模板方法模式,主要是利用了inheritance。

书中有写:The template method calls primitive operations as well as operations defined in AbstractClass or those of others.



热点排行