Intro to Design Patterns
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 45 of 65.
A design pattern is a known, named way to arrange classes for a problem that comes back in program after program. It is not a library and not code to copy: it describes which objects exist, what each one is responsible for, and how they work together. You write the code yourself, shaped to your game.
Patterns also give developers shared words. "Enemies come from a factory" or "the health bar observes the player" tells a teammate how the code is organized before they open a file.
Here is a problem a pattern solves. Starting a level means talking to three objects, and every script that starts a level repeats these lines:
var music := MusicPlayer.new()
var level_map := LevelMap.new()
var hud := Hud.new()
music.play("forest.ogg")
level_map.load_map(1)
hud.show_hearts(3)The Facade pattern puts one class in front of those objects and gives it one simple method:
# game_facade.gd
class_name GameFacade
extends RefCounted
var music := MusicPlayer.new()
var level_map := LevelMap.new()
var hud := Hud.new()
func start_level(number: int) -> void:
music.play("forest.ogg")
level_map.load_map(number)
hud.show_hearts(3)# main.gd
var game := GameFacade.new()
game.start_level(1)Music: playing forest.ogg
Map: level 1 loaded
HUD: hearts 3The rest of the program calls start_level(), and when starting a level changes, you edit one file.
Patterns are grouped by the problem they solve:
- Creational patterns control how objects are created: Singleton, Factory.
- Structural patterns combine objects into larger structures: Facade, Adapter, Decorator, Composite.
- Behavioral patterns organize how objects work together: Observer, Strategy, Command, Template Method, State.
This chapter and the next one cover these patterns. Each one is built from what you already know: classes in their own files, inheritance, polymorphism, composition and signals.
Challenge
EasyA game starts and quits levels through three objects that are already written: MusicPlayer (music_player.gd), LevelMap (level_map.gd) and Hud (hud.gd). Write the facade GameFacade in front of them:
- It creates one
MusicPlayer, oneLevelMapand oneHudin its member variables. start_level(number, hearts)plays the tracklevel_N.ogg(N is the level number), orboss.oggwhen the number is a multiple of5, then loads the map of that level, then shows the hearts.quit_level()hides the HUD, then stops the music.
The supplied code reads how many commands follow, then one command per line: start NUMBER HEARTS or quit. For start 5 2 and quit the output is:
Music: playing boss.ogg
Map: level 5 loaded
HUD: hearts 2
HUD: hidden
Music: stoppedYour code goes in game_facade.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 game := GameFacade.new()
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
if parts[0] == "start":
game.start_level(int(parts[1]), int(parts[2]))
elif parts[0] == "quit":
game.quit_level()
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 Calculator2Class 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