Skip to content

Instantly share code, notes, and snippets.

// Entity One: Weapon
protocol Weapon{
func fire(); // Weapon can be fire
}
// The Context: Player, who can fire a weapon
class Player{
var currentWeapon:Weapon?;
// Fire: call the `fire` method of the weapon
// all implementation of Explosve that also implements Weapon, call `detonate` in `fire` method
extension Explosive where Self:Weapon{
func fire(){
self.detonate()
}
}
// Finally, extend Grenade to Weapon
extension Grenade:Weapon{}
struct WeaponAdapterForExplosive:Weapon{
var explosive:Explosive
func fire(){
self.explosive.detonate()
}
}
player.currentWeapon = WeaponAdapterForExplosive(explosive:Grenade())
player.fire()
protocol Explosive{
func detonate()
}
struct Grenade:Explosive{
func detonate(){
print("A grenade exploded!")
}
}
let player = Player()
player.currentWeapon = AK47()
player.currentWeapon?.fire() // prints "Firing with AK47"
struct AK47:Weapon{
func fire(){
print("Firing with AK47")
}
}
// Entity One: Weapon
protocol Weapon{
func fire(); // Weapon can be fire
}
// The Context: Player, who can fire a weapon
class Player{
var currentWeapon:Weapon?;
// Fire: call the `fire` method of the weapon
class Player{
var currentWeapon:Weapon?;
var currentBlade:Blade?;
var currentExplosive:Explosive?;
func select(weapon:Weapon){
self.currentWeapon = weapon;
}
func select(blade:Blade){
self.currentBlade = blade;
// This is the player definition
class Player{
// Current weapon i.e. the current strategy/behavior
var currentWeapon:Weapon?;
// Dynamically sets the current weapon
func select(weapon:Weapon){
self.currentWeapon = weapon;
}
// This is the protocol, that defines family of weapon
protocol Weapon{
func fire(); // Weapon can be fire
}
// This is the player definition
class Player{
// Current weapon i.e. the current strategy/algorithm
var currentWeapon:Weapon?;