Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

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

I am reading about Template design pattern. As per my current understanding, Template design pattern can be used when we have an algorithm with defined set of processes(methods) to be done in order. Main players are

1.Abstract Template class providing a template method defining the processes (methods) and the order of execution. Usually this method is made final, so as its behavior is not modified. Few of the processes(methods) mentioned in the template method are provided with default implementation and others depending upon the concrete classes extending the Abstract template class types are left as abstract.

2.Concrete classes extending the Template method. These override the default methods if necessary and provided the implementation for the abstract methods defined in the Abstract Template class.

I tried searching for its implementation in JDK, i looked at java.io classes after reading that these classes implement this pattern. I was not able to find any method defining a set of processes(methods) and the order of execution.

Please provide your valuable inputs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...