Skip to content

Instantly share code, notes, and snippets.

@okabe-yuya
Last active September 8, 2022 15:21
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 okabe-yuya/7a6ef3a4ba60ad3dcb590d9d2c0787fc to your computer and use it in GitHub Desktop.
Save okabe-yuya/7a6ef3a4ba60ad3dcb590d9d2c0787fc to your computer and use it in GitHub Desktop.
class Sward
attr_reader :options
def initialize
@options = {}
end
def cost
raise NotImplementedError.new("#{self.class}##{__method__} が実装されていません")
end
def set_option(key, val)
@options[key] = val
end
end
class SwardMaterial # < Sward 別に継承している必要はない => 継承より委譲
def initialize(sward)
@sward = sward
end
def set(material)
@sward.set_option(:material, material)
@sward
end
end
class AddAttribute # < Sward 別に継承している必要はない => 継承より委譲 < Sward
def initialize(sward)
@sward = sward
end
def set(attribute)
new_options = (@sward.options[:attribute] || []).push(attribute)
@sward.set_option(:attribute, new_options)
@sward
end
end
sward = Sward.new()
sward = SwardMaterial.new(sward).set('steel')
sward = AddAttribute.new(sward).set('fire')
sward = AddAttribute.new(sward).set('frozen')
p sward # #<Sward:0x000014b7a9599348 @options={:material=>"steel", :attribute=>["fire", "frozen"]}>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment