gpt4 book ai didi

ruby - 策略模式 - DRY 方式来定义一些但不是所有子策略中使用的方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:57:15 24 4
gpt4 key购买 nike

我正在我的 Ruby 项目中实现一个策略模式,但遇到了一个轻微的代码风格问题。

假设我有三个继承自通用基本策略类的策略类。这三种策略中的两种将需要访问一种方法——第三种不使用它。所以我的直觉是将常用方法放在Base策略中:

class FoodStrategies::Base
# Used by 2 of the 3 child strategy classes
def add_hot_sauce
puts "Food is now spicy"
end

def eat
raise NotImplementedError
end
end

class FoodStrategies::Taco < FoodStrategies::Base
def eat
add_hot_sauce
puts "Spicy and delicious!"
end
end

class FoodStrategies::Burrito < FoodStrategies::Base
def eat
add_hot_sauce
puts "Spicy and tasty!"
end
end

class FoodStrategies::Cereal < FoodStrategies::Base
def eat
puts "Yum"
end
end

从技术上讲,这意味着 FoodStrategies::Cereal 也将具有 add_hot_sauce 方法,但不会使用它。这对我来说似乎是一种代码味道。所以我想知道是否有更合适的方法来保持事物干燥而不向不打算使用它们的策略提供方法。

我试着用谷歌搜索看看其他人在这种情况下做了什么,但令人惊讶的是我没有找到任何东西。我也有想法为这些策略添加另一层继承,并将方法放在新的继承层中:

class FoodStrategies::SpicyFood < FoodStrategies::Base
def add_hot_sauce
puts "Food is now spicy"
end
end

class FoodStrategies::SpicyFood::Taco < FoodStrategies::Base
# etc.
end

这样我就可以将所需的行为隔离到 SpicyFood 的子级,这意味着 TacoBurrito 将获得 add_hot_sauce 方法,但 Cereal 不会。然而,我看到的策略模式的例子并不建议或鼓励像这样进行多层继承,而是所有的例子都只使用了一层继承。

是否有任何共识或标准可接受的方法来解决这个问题?

最佳答案

如果你根本不想将未使用的方法暴露给 children ,你应该为个别行为使用模块

class FoodStrategies::Base
def eat
raise NotImplementedError
end
end

module CanBeSpicy
def add_hot_sauce
puts "Food is now spicy"
end
end

class FoodStrategies::Taco < FoodStrategies::Base
include CanBeSpicy
def eat
add_hot_sauce
puts "Spicy and delicious!"
end
end

class FoodStrategies::Burrito < FoodStrategies::Base
include CanBeSpicy
def eat
add_hot_sauce
puts "Spicy and tasty!"
end
end

class FoodStrategies::Cereal < FoodStrategies::Base
def eat
puts "Yum"
end
end

如果你有一堆行为要添加,你可以传递多个 like

include BehaviorA, BehaviorB

当然还有很多其他方法可以做到这一点,但我认为在这种情况下,虽然模块方法可能看起来更死记硬背,因为您必须手动为每个类指定行为列表而不是在父类中执行,这与更简单的方法无关。

关于ruby - 策略模式 - DRY 方式来定义一些但不是所有子策略中使用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48954362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com