Template Method Pattern in Java: Explanation & Practice
Implement template method pattern
Problem summary
Create abstract Game with template play() method. Subclasses implement specific steps.
Starter code
// Abstract Game with:
// - final void play() - calls init, start, end
// - abstract init(), start(), end()
// Chess and Cricket implement differently
public class Main {
public static void main(String[] args) {
// Play chess game
}
}Expected output and test cases
- Chess game
Setting up chess board Chess game started Checkmate!
- Cricket game
Toss coin Play cricket Match over
- Poker game
Deal cards Play poker Showdown!
Hints
- Template method is final in parent
- Steps are abstract, implemented by children
- Algorithm structure stays same
Related Inheritance exercises
- Practice Multiple Interfaces in Java
- Practice Comparable Implementation in Java
- Practice Simple Factory Pattern in Java
Practice all Inheritance exercises · Run this idea in the Java compiler