Decorator Pattern
Category:
Adding functionality to objects by creating new small classes instead of adding and changing methods in old classes.
class Robot
def initialize(name)
@name = name
end
def name
puts @name
end
end
class Aged < SimpleDelegator
def initialize(source, age=0)
super(source)
@age = age
end
def age
puts @age
end
end
class Ranked < SimpleDelegator
def initialize(source, rank=10)
super(source)
@rank = rank
end
def rank
puts @rank
end
end
class HumanFriendly < SimpleDelegator
def age
puts "My age is:"
super
end
def rank
puts "My rank is:"
super
end
def name
puts "My name is:"
puts "Friend of Humanity"
end
end
robot = HumanFriendly.new(Ranked.new(Aged.new(Robot.new("Destroyer of Humanity"))))
robot.name
robot.age
robot.rank
# output
# My name is:
# Friend of Humanity
# My age is:
# 0
# My rank is:
# 10