Last active
June 23, 2021 12:39
-
-
Save Neko3000/6879a7b3a96282b64c6dcf5bb633e820 to your computer and use it in GitHub Desktop.
Decorator pattern in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Character { | |
func getHealth() -> Int | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Core Component | |
protocol Character { | |
func getHealth() -> Int | |
} | |
// Concrete Components | |
struct Orc: Character { | |
func getHealth() -> Int { | |
return 10 | |
} | |
} | |
struct Elf: Character { | |
func getHealth() -> Int { | |
return 5 | |
} | |
} | |
// Decorator | |
protocol CharacterType: Character { | |
var base: Character { get } | |
} | |
// Concrete Decorators | |
struct Warlord: CharacterType { | |
let base: Character | |
func getHealth() -> Int { | |
return 50 + base.getHealth() | |
} | |
// New responsibility | |
func battleCry() { | |
print("RAWR") | |
} | |
} | |
struct Epic: CharacterType { | |
let base: Character | |
func getHealth() -> Int { | |
return 30 + base.getHealth() | |
} | |
} | |
let orc = Orc() | |
let hp = orc.getHealth() // 10 | |
let orcWarlord = Warlord(base: orc) | |
let hp = orcWarlord.getHealth() // 60 | |
let epicOrcWarlord = Epic(base: orcWarlord) | |
let hp = epicOrcWarlord.getHealth() // 90 | |
let doubleEpicOrcWarlord = Epic(base: epicOrcWarlord) | |
let hp = doubleEpicOrcWarlord.getHealth() // 120 | |
let elf = Elf() | |
let hp = elf.getHealth() // 5 | |
let elfWarlord = Warlord(base: elf) | |
let hp = elfWarlord.getHealth() // 55 | |
elfWarlord.battleCry() // "RAWR" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct John: Character { | |
func getHealth() -> Int { | |
return 1 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Orc: Character { | |
func getHealth() -> Int { | |
return 10 | |
} | |
} | |
struct OrcBarbarian: Character { | |
func getHealth() -> Int { | |
return 15 | |
} | |
} | |
struct OrcWarlord: Character { | |
func getHealth() -> Int { | |
return 20 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment