Created
May 18, 2019 20:02
-
-
Save uxdxdev/061773d8908ed61e186d5f5d263166f6 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 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