Skip to content

Instantly share code, notes, and snippets.

@ryz310
Created September 28, 2019 08:47
Show Gist options
  • Save ryz310/d2a2da45a60323dd41d45481a90a3a52 to your computer and use it in GitHub Desktop.
Save ryz310/d2a2da45a60323dd41d45481a90a3a52 to your computer and use it in GitHub Desktop.
昔の蛇口と現代の蛇口をオブジェクト指向で表現してみた。勉強会用資料。
class Water
attr_reader :temperature, :amount
def initialize(temperature:, amount:)
@temperature = temperature
@amount = amount
end
def +(other)
total_amount = self.amount + other.amount
total_calorie = self.temperature * self.amount + other.temperature * other.amount
Water.new(temperature: total_calorie.to_f / total_amount, amount: total_amount)
end
end
class ColdWater < Water
TEMPERATURE = 10
def initialize(amount:)
super(temperature: TEMPERATURE, amount: amount)
end
end
class HotWater < Water
TEMPERATURE = 42
def initialize(amount:)
super(temperature: TEMPERATURE, amount: amount)
end
end
class OldStyleFaucet
attr_reader :hot_water_amount, :cold_water_amount
def initialize
@hot_water_amount = 0
@cold_water_amount = 0
end
def turn_hot_water_faucet(amount:)
@hot_water_amount = amount
end
def turn_cold_water_faucet(amount:)
@cold_water_amount = amount
end
def pour
HotWater.new(amount: hot_water_amount) + ColdWater.new(amount: cold_water_amount)
end
end
class CurrentStyleFaucet
attr_accessor :temperature, :amount
def initialize(temperature:, amount:)
@temperature = temperature
@amount = amount
end
def pour
HotWater.new(amount: hot_water_amount) + ColdWater.new(amount: cold_water_amount)
end
private
def hot_water_amount
amount.to_f * (temperature - ColdWater::TEMPERATURE) / (HotWater::TEMPERATURE - ColdWater::TEMPERATURE)
end
def cold_water_amount
amount - hot_water_amount
end
end
# ==============================================================================
old_style_faucet = OldStyleFaucet.new
old_style_faucet.turn_hot_water_faucet(amount: 80)
old_style_faucet.turn_cold_water_faucet(amount: 20)
old_style_faucet.pour # => #<Water @amount=100, @temperature=35.6>
old_style_faucet.turn_hot_water_faucet(amount: 90)
old_style_faucet.turn_cold_water_faucet(amount: 10)
old_style_faucet.pour # => #<Water @amount=100, @temperature=38.8>
old_style_faucet.turn_hot_water_faucet(amount: 95)
old_style_faucet.turn_cold_water_faucet(amount: 5)
old_style_faucet.pour # => #<Water @amount=100, @temperature=40.4>
# ==============================================================================
current_style_faucet = CurrentStyleFaucet.new(temperature: 40, amount: 100)
current_style_faucet.pour # => #<Water @amount=100.0, @temperature=40.0>
current_style_faucet.send(:hot_water_amount) # => 93.75
current_style_faucet.send(:cold_water_amount) # => 6.25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment