Skip to content

Instantly share code, notes, and snippets.

@uxdxdev
Created May 18, 2019 20:02
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/061773d8908ed61e186d5f5d263166f6 to your computer and use it in GitHub Desktop.
Save uxdxdev/061773d8908ed61e186d5f5d263166f6 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 Sprinkles
include Decorator
def operation
puts "Sprinkles added"
super
end
end
class Fruit
include Decorator
def operation
puts "Fruit added"
super
end
end
class Cake
include Component
def initialize(strategy)
@strategy = strategy
end
def operation
@strategy.execute
end
def change_strategy(strategy)
@strategy = strategy
end
end
module CookingStrategy
def execute
raise "CookingStrategy error"
end
end
class Oven
include CookingStrategy
def execute
puts "Oven cooked"
end
end
class Microwave
include CookingStrategy
def execute
puts "Microwave cooked"
end
end
# use strategy
oven_strategy = Oven.new
cake = Cake.new(oven_strategy)
cake.operation
# swap strategy
microwave_strategy = Microwave.new
cake.change_strategy(microwave_strategy)
cake.operation
# add decorators
cake = Sprinkles.new(Fruit.new(cake))
cake.operation
# remove decorator
cake = cake.remove
cake.operation
# remove decorator
cake = cake.remove
cake.operation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment