Template Method Pattern
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 53 of 65.
The Template Method pattern fixes the order of an algorithm's steps in a parent class and lets each subclass fill in some of the steps. The parent method that runs the steps is the template method.
# level.gd
@abstract
class_name Level
extends RefCounted
func play() -> void:
print("Loading ", get_level_name())
spawn_enemies()
print("Level complete!")
@abstract func get_level_name() -> String
@abstract func spawn_enemies() -> voidplay() is the template: every level loads, spawns its enemies and completes, in this order. The steps that differ are abstract, so every subclass has to write them:
# forest_level.gd
class_name ForestLevel
extends Level
func get_level_name() -> String:
return "Forest"
func spawn_enemies() -> void:
print("3 wolves appear")CaveLevel is written the same way, with the name "Cave" and 5 bats appear.
# main.gd
var levels: Array[Level] = [ForestLevel.new(), CaveLevel.new()]
for level in levels:
level.play()Loading Forest
3 wolves appear
Level complete!
Loading Cave
5 bats appear
Level complete!A step can also have a default in the parent that a subclass may override. Such an optional step is called a hook:
# level.gd
func play() -> void:
print("Loading ", get_level_name())
spawn_enemies()
if has_boss():
print("The boss arrives")
print("Level complete!")
func has_boss() -> bool:
return falseOnly a level that overrides has_boss() to return true gets the boss line. The subclasses write steps and the parent decides when they run, so a subclass leaves play() alone and every level follows the same order.
Challenge
MediumA game exports its scores in two formats with the same steps. Rows are Dictionaries with a "name" and a "score".
- In
exporter.gd, write the template methodexport_rows(rows): it printsheader(), thenformat_row(row)for every row, thenfooter(rows). A header or footer that is an empty string is not printed. The hooksheader()andfooter()return""by default, andformat_row()is abstract. CsvExporter: the header isname,score, and a row isAda,12. No footer.ListExporter: no header, a row is* Ada scored 12, and the footer isPlayers: Nwith the number of rows.
The supplied code reads the format (csv or list), how many rows follow, then one NAME SCORE row per line. For list with Ada 12 and Bo 7 the output is:
* Ada scored 12
* Bo scored 7
Players: 2Your code goes in exporter.gd, csv_exporter.gd and list_exporter.gd. main.gd holds the supplied input/output code and cannot be edited.
Try it yourself
extends Node
func _ready():
# Supplied input/output code: keep it as it is
var style := OS.read_string_from_stdin()
var rows: Array = []
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
rows.append({"name": parts[0], "score": int(parts[1])})
var exporter: Exporter = CsvExporter.new()
if style == "list":
exporter = ListExporter.new()
exporter.export_rows(rows)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self KeywordMethodsPropertiesConstructor (_init)Recap - Simple Calculator4Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator7Signals
What is a Signal?Declaring and EmittingConnecting to SignalsSignals with ArgumentsRecap - Health System10Design Patterns Part 2
Command PatternAdapter PatternDecorator PatternTemplate Method PatternState PatternComposite Pattern2Class Properties
Instance vs Static VariablesStatic FunctionsProperty SettersProperty GettersPrivate by ConventionRecap - Bank Account Manager5Encapsulation
Public and Private MembersValidation with SettersInformation HidingRead-Only PropertiesRecap - Student Records System8Advanced OOP Concepts
Composition vs InheritanceInner ClassesNodes as ComponentsRefCounted vs NodeEnums in Classes11Project: Library Management
Project OverviewBook and User Classes3Inheritance
Basic InheritanceThe super KeywordMethod OverridingInheritance ChainsType Checks with isRecap - Employee Hierarchy6Special Methods
Virtual Methods IntroductionThe _to_string MethodCustom IteratorsRecap - Custom List9Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy PatternPractice on your own: Online GDScript compiler