Template design pattern in JDK, could not find a method defining set of methods to be executed in order

北城以北 提交于 2019-11-28 01:29:34

A simple example is java.io.OutputStream.

The template method is
public void write(byte b[], int off, int len).

It calls the abstract method
public abstract void write(int b),
which must be implemented by a subclass of OutputStream.

In this case the invariant portion of the template is the basic error handling that is common to every OutputStream, while the variant portion of the template is the actual writing, which is specific to each concrete implementation.

Your understanding of the pattern is correct; however, it needn't be that complex. Basically, any concrete method which calls an abstract method in the same class is a template method.

To be more specific:

Non-abstract methods calling abstract methods inside their implementation can be categorized as Template Methods.

Template_method define the program skeleton of an algorithm in an operation, defering some steps to subclasses. If you define complete operation as an abstract method, sub-classes will have full control to change the skeleton of the algorithm and hence abstract methods are not classified as Template methods.

e.g. Reader class in IO.

 public int read() throws IOException {
        char cb[] = new char[1];
        if (read(cb, 0, 1) == -1) // this is an abstract method
            return -1;
        else
            return cb[0];
    }

Here

abstract public int read(char cbuf[], int off, int len) throws IOException; is abstract method.

Implementation of this method can be found in BufferedReader

public int read(char cbuf[], int off, int len) throws IOException {

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!