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

  1. Template method is final in parent
  2. Steps are abstract, implemented by children
  3. Algorithm structure stays same

Related Inheritance exercises

Practice all Inheritance exercises · Run this idea in the Java compiler