design-patternstemplate-method-pattern

Where should we use Template Method - pattern?


Can anyone let me know some example situations where Template Method - pattern should be used?

Give me some real-world use from your own experience.

(I have so far found it useful only for mapping data in the DA layer. Sorry!!!)


Solution

  • I tried to give you some real-world examples, and some common situations where Template Method pattern should be used.

    function0: function1: ... functionN:

    1       1               1
    2       2               2
    ...     ...             ...
    5       6               n
    3       3               3
    4       4               4
    ...     ...             ...
    

    As you can see, section cods 5, 6, n are different vary from one function to another function, however you have shared sections such as 1,2,3,4 that are duplicated. Lets consider a solution with one of famous java libraries.

    public abstract class InputStream implements Closeable {
    
        public abstract int read() throws IOException;
    
        public int read(byte b[], int off, int len) throws IOException {
            ....
    
            int c = read();
            ....
        }
    
        ....
    
    }
    
    public class ByteArrayInputStream extends InputStream {  
    
        ...
    
        public synchronized int read() {
            return (pos < count) ? (buf[pos++] & 0xff) : -1;
            }
        ...
    }