Ruby 使用装饰图案展开对象时未发生求和

Ruby 使用装饰图案展开对象时未发生求和,ruby,design-patterns,decorator,Ruby,Design Patterns,Decorator,我正在尝试使用Decorator模式方法来解决这个问题。我使用和作为参考。我试图对我创建的项目的适用税进行汇总,但我只能获得最后一个未包装对象所应用的税 module SalesTaxDeco class Item attr_accessor :price def initialize(price) @price = price end def sales_tax end end class SalesTax

我正在尝试使用Decorator模式方法来解决这个问题。我使用和作为参考。我试图对我创建的项目的适用税进行汇总,但我只能获得最后一个未包装对象所应用的税

module SalesTaxDeco

  class Item

    attr_accessor :price

    def initialize(price)
      @price = price
    end

    def sales_tax
    end

  end

  class SalesTax

    def price
      @component.price
    end

    def initialize(component)
      @component = component
    end

    def sales_tax
      ((@component.price * 0.10)*(1/0.05).ceil)/(1/0.05)
    end
  end

  class ImportDuty

    def price
      @component.price
    end

    def initialize(component)
      @component = component
    end

    def sales_tax
      ((@component.price * 0.5)*(1/0.05).ceil)/(1/0.05)
    end
  end
end
我已经创建了一个项目作为

def test_imported_perfume_is_taxed
    item = Item.new 47.50
    assert_equal 7.15, SalesTax.new(ImportDuty.new(item)).sales_tax
end
但我得到的答案只有4.75。有什么好处?我哪里做错了

谢谢。

ImportDuty#sales#tax
不被调用,因为
sales#tax
不调用基础组件的sales#tax方法

请尝试以下操作:

class Item
  ....
  def sales_tax
    0
  end
end

class SalesTax
  ...
  def sales_tax
    @component.sales_tax + ((@component.price * 0.10)*(1/0.05).ceil)/(1/0.05)
  end
end

class ImportDuty
  ...
  def sales_tax
    @component.sales_tax + ((@component.price * 0.05)*(1/0.05).ceil)/(1/0.05)
  end
end
使用上述代码,
salesax.new(ImportDuty.new(Item.new 47.50)).salesax产生
7.125