Here has four steps to demonstrate template method pattern:
1. Create an abstract class with a template method being final.
package com.example.pattern.template;
public abstract class Game {
abstract void initializeGame();
abstract void playGame();
abstract void endGame();
/**
* template method
*/
public final void play() {
initializeGame();
playGame();
endGame();
}
}
2. Create concrete classes extending the above class.
package com.example.pattern.template;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FishingStrike extends Game {
@Override
void initializeGame() {
log.debug("Fishing Strike initialized!");
}
@Override
void playGame() {
log.debug("Fishing Strike started! Enjoy the game!");
}
@Override
void endGame() {
log.debug("Fishing Strike finished! See you!");
}
}
package com.example.pattern.template;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MiniGolfKing extends Game {
@Override
void initializeGame() {
log.debug("Mini Golf King initialized!");
}
@Override
void playGame() {
log.debug("Mini Golf King started! Enjoy the game!");
}
@Override
void endGame() {
log.debug("Mini Golf King finished! See you!");
}
}
3. Create a demo class to use the Game's template method play() to demonstrate a defined way of playing game.
package com.example.pattern.template;
import org.springframework.stereotype.Component;
@Component
public class TemplatePatternDemo {
/**
* play fishing strike game
*/
public void playFishingStrike() {
Game fishingStrike = new FishingStrike();
fishingStrike.play();
}
/**
* play mini golf king game
*/
public void playMiniGolfKing() {
Game miniGolfKing = new MiniGolfKing();
miniGolfKing.play();
}
}
4. Autowired TemplatePatternDemo to play execute methods and verify output
package com.example.test;
import com.example.pattern.template.TemplatePatternDemo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Bean
CommandLineRunner run(TemplatePatternDemo demo) {
return args -> {
demo.playFishingStrike();
demo.playMiniGolfKing();
};
}
}
[main] c.e.pattern.template.FishingStrike : Fishing Strike initialized!
[main] c.e.pattern.template.FishingStrike : Fishing Strike started! Enjoy the game!
[main] c.e.pattern.template.FishingStrike : Fishing Strike finished! See you!
[main] c.example.pattern.template.MiniGolfKing : Mini Golf King initialized!
[main] c.example.pattern.template.MiniGolfKing : Mini Golf King started! Enjoy the game!
[main] c.example.pattern.template.MiniGolfKing : Mini Golf King finished! See you!