I don't know much about the proper use of inheritance and delegation, so I summarized it.
It is to take over the function from another class and create a new class.
Create a Foo class by inheriting all the methods from the Base class
class Base
def message
'ok'
end
end
class Foo < Base; end
foo = Foo.new
puts foo.message
# => ok
It is to delegate a specific process (responsibility) to a method of another class.
Delegate the message method of the Base class to the Foo class
class Base
def message
'ok'
end
end
require 'forwardable'
class Foo
extend Forwardable
attr_reader :mess
def initialize
@mess = Base.new
end
def_delegator :mess, :message
end
foo = Foo.new
puts foo.message
# => ok
Whether you are a fledgling engineer or an experienced Tsuyotsuyo engineer, the role of a programmer is the same. So, let's inherit the Progurammer class and inherit the function as it is.
class Programmer
def initialize(type, langages)
@type = type
@langages = Array(langages)
end
def type_is
puts "I#{type}is."
end
def langage_is
str = ''
langages.each do |lang|
str += "#{lang} "
end
puts "I#{str}Can handle the language of"
end
def klass_is
str = case self.class.name
when 'TsuyoTsuyo'
'Strong engineer'
when 'Kakedashi'
'Fledgling engineer'
end
puts "I#{str}is."
end
private
attr_accessor :type, :langages
end
class TsuyoTsuyo < Programmer; end
class Kakedashi < Programmer; end
tsuyo = TsuyoTsuyo.new('Backend', %w[C C++ Python Go Ruby])
tsuyo.type_is
tsuyo.langage_is
tsuyo.klass_is
kake = Kakedashi.new('Frontend', %w[HTML CSS jQuery])
kake.type_is
kake.langage_is
kake.klass_is
Programmers and designers have different roles. So in this case we will use delegation and only the type_is
method will be inherited from the Programmer class.
require 'forwardable'
class Programmer
def initialize(type, langages)
@type = type
@langages = Array(langages)
end
def type_is
puts "I#{type}is."
end
private
attr_accessor :type, :langages
end
class Designer
extend Forwardable
def initialize(type, skills)
@programmer = Programmer.new(type, nil)
@type = type
@skills = Array(skills)
end
def_delegator :@programmer, :type_is
private
attr_accessor :type, :skills
end
class IkeIke < Designer; end
ikeike = IkeIke.new('WebDesigner', %w[HTML CSS Adobe JavaScript])
ikeike.type_is #This type_is method`Programmer`Method inherited from class
Thank you for reading this far. I hope it will be an opportunity to review my code.
I usually develop web services with Rails, but I don't think there are many occasions to use delegation. It is also true that I used to say "inheritance !!" It is difficult to judge whether the inheritance relationship is good or whether it is better to use delegation, but in the future I decided to implement it including the option of using delegation.
Recommended Posts