class Order
attr_reader :amount, :discount_strategy
def initialize(amount, discount_strategy)
@amount = amount
@discount_strategy = discount_strategy
end
def discount
discount_strategy.calculate(amount)
end
end
# 割引戦略インターフェース
class DiscountStrategy
def calculate(amount)
raise NotImplementedError, 'サブクラスで実装してください'
end
end
class RegularDiscount < DiscountStrategy
def calculate(amount)
amount * 0.1
end
end
class PremiumDiscount < DiscountStrategy
def calculate(amount)
amount * 0.2
end
end
regular_order = Order.new(1000, RegularDiscount.new)
puts regular_order.discount #=> 100.0
premium_order = Order.new(1000, PremiumDiscount.new)
puts premium_order.discount #=> 200.0