Created
May 18, 2019 17:48
-
-
Save uxdxdev/1306dba351af1d2dbb9af692d2cb2f3a to your computer and use it in GitHub Desktop.
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
module Component | |
def operation | |
raise "Component error" | |
end | |
end | |
module Decorator | |
include Component | |
def initialize(component) | |
@component = component | |
end | |
def operation | |
@component.operation | |
end | |
def remove | |
return @component | |
end | |
end | |
class Fire | |
include Decorator | |
def operation | |
puts "Fire added" | |
super | |
end | |
end | |
class Ice | |
include Decorator | |
def operation | |
puts "Ice added" | |
super | |
end | |
end | |
class Wizard | |
include Component | |
def initialize(strategy) | |
@strategy = strategy | |
end | |
def operation | |
@strategy.execute | |
end | |
def change_strategy(strategy) | |
@strategy = strategy | |
end | |
end | |
module MagicStrategy | |
def execute | |
raise "MagicStrategy error" | |
end | |
end | |
class Wand | |
include MagicStrategy | |
def execute | |
puts "Wand magic" | |
end | |
end | |
class Sword | |
include MagicStrategy | |
def execute | |
puts "Sword magic" | |
end | |
end | |
# use magic strategy | |
wand_strategy = Wand.new | |
wizard = Wizard.new(wand_strategy) | |
wizard.operation | |
# swap strategy | |
sword_strategy = Sword.new | |
wizard.change_strategy(sword_strategy) | |
wizard.operation | |
# add types of magic decorators | |
wizard = Ice.new(Fire.new(wizard)) | |
wizard.operation | |
# remove decorator | |
wizard = wizard.remove | |
wizard.operation | |
# remove decorator | |
wizard = wizard.remove | |
wizard.operation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment