http://www.35java.com/zhibo/forum.php?mod=viewthread&tid=288&extra=page%3D1



仅仅是抽象类别与具体类别实作的关系而已,有些人常问抽象类别与介面的区别为何,Template Method模式可以提供其中一个答案,例如:
  • AbstractClass.java
public abstract class AbstractClass {
    public void templateMethod() {
        // step by step template to solve something
        // implementor should follow those step
        opStep1();
        opStep2();
        opStep3();
    }

    public abstract void opStep1();
    public abstract void opStep2();
    public abstract void opStep3();
}

  • ConcreteClass.java
public class ConcreteClass extends AbstractClass {
    public abstract void opStep1() {
        // implement the real operation
    }

    public abstract void opStep2() {
        // implement the real operation
    }

    public abstract void opStep3() {
        // implement the real operation
    }
}
对于一些程式而言,我们希望规定一些处理的步骤、流程或骨架,就像是上例中的step1到step3一样,至于流程中的step1到step3如何实作并不规定,而留给实作的人自行决定,这就是Template Method模式的目的。

抽象类别与介面的差别之一,也正在于抽象类别可以先实作其中一些方法,而介面则是完全仅规定接口,使用Template Method模式就可以看出两者之间在应用上的一个差别。

仅以step1到step3这样的操作来看Template Method模式,似乎彰显示不出其实作骨架,而将实作部份留待子类的实用性,在 Gof书中所举的例子是与 Factory Method 模式结合的一个例子;通常开启一个档案的流程是相似的,例如文字档或二进位档,不外乎检查档案是否可开启、读取档案、设定显示等流程,可以使用Template Method模式来规范这个流程:
public abstract class Application {
    // .....

    public void openDocument(String name) {
        // Template Method
        if(!canOpenDocument(name)) { // unable to open file
            // show error message, throw exception
            return;
        }

        Document doc = createDocument(); // Factory Method

        if(doc != null) {
            _docs.addDocument(doc);
            // Template Method
            aboutToOpenDocument(doc);
             doc.open();
             doc.doRead();
        }
    }

    // Factory Method
    public abstract Document createDocument();

    // Template Method
    public abstract boolean canOpenDocument(String name);
    public abstract void aboutToOpenDocument(Document doc);
}


public class MyApplication extends Application {
    // implement Factory Method
    public void Document createDocument() {
        return new MyDocument();
    }

    // implement Template Method
    public void boolean canOpenDocument(String name) {
        // implemented code here
    }

    public void aboutToOpenDocument(Document doc) {
        // implemented code here
    }
}


Factyro Method模式将实际要创建的物件推迟至子类中决定,而TemplateMethod模式则是将流程框架的实作留待子类来解决,事实上在这个例子中,您也可以将createDocument()看作是TemplateMethod模式中的一个方法,从物件创建的角度来看它是Factory Method,而从流程框架的角度来看,它则是TemplateMethod模式的一个方法实作。

相关文章: