Design patterns
patterns22TemplateMethodPattern
- Path
- pkg8patterns/patterns22TemplateMethodPattern.java
- Package
- pkg8patterns
- Study order
- 22
- Run
- Single-file source launch
- Command
- java pkg8patterns/patterns22TemplateMethodPattern.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg8patterns;2 3/*4 * Template Method (Behavioral)5 * ----------------------------6 * INTENT: define the skeleton of an algorithm in a base method, deferring some7 * steps to subclasses without changing the algorithm's structure.8 * UML: AbstractClass + templateMethod() (final) + step1()/step2() (abstract).9 * PROS: code reuse; enforce invariant algorithm structure ("Hollywood principle").10 * CONS: inheritance-based (less flexible than composition/strategy).11 * REAL-WORLD: java.util.AbstractList, InputStream.read, HttpServlet.service.12 */13public class patterns22TemplateMethodPattern {14 15 static abstract class DataProcessor {16 // The template method: fixed steps, variable implementations17 final void process() {18 read();19 transform();20 write();21 }22 abstract void read();23 abstract void transform();24 void write() { System.out.println(" writing result (default)"); } // hook with default25 }26 27 static class CsvProcessor extends DataProcessor {28 void read() { System.out.println("CSV: read rows"); }29 void transform() { System.out.println("CSV: split by comma"); }30 }31 static class JsonProcessor extends DataProcessor {32 void read() { System.out.println("JSON: read document"); }33 void transform() { System.out.println("JSON: parse tree"); }34 @Override void write() { System.out.println(" JSON: pretty-print result"); } // override hook35 }36 37 public static void main(String[] args) {38 System.out.println("-- CSV --"); new CsvProcessor().process();39 System.out.println("-- JSON --"); new JsonProcessor().process();40 }41}