Skip to content

Instantly share code, notes, and snippets.

@uxdxdev
Created May 18, 2019 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uxdxdev/1306dba351af1d2dbb9af692d2cb2f3a to your computer and use it in GitHub Desktop.
Save uxdxdev/1306dba351af1d2dbb9af692d2cb2f3a to your computer and use it in GitHub Desktop.
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