gpt4 book ai didi

c++ - 决策、复杂条件和规划易于维护

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:13 26 4
gpt4 key购买 nike

我正在尝试找到一种优雅的方式来实现易于维护的决策算法,因为决策的条件可能经常变化。

我将尝试更具体地举一个例子:

假设我正在尝试管理一家餐厅厨房的 cooking 厨师团队。

每个厨师都知道如何 cooking 3 种馅饼:苹果馅饼、南瓜馅饼和覆盆子馅饼以及 2 种披萨:奶酪披萨和培根披萨。他们都知道如何 cooking 一切。

现在,我想向这些主管发送关于客户即将到来的事情的命令。

条件是:

一个酋长一次只能做一个馅饼。例如,如果我命令厨师做一个苹果派,我不能命令他做覆盆子派或南瓜派,除非苹果派做好了或者我发送了取消苹果派的请求。

我可以让厨师一次最多煮 5 个比萨饼,因为它是为不同的客户准备的。

我想创建一个算法,返回我被允许发送给特定厨师的一组订单,关于他已经在做什么。

我正在使用 C++。
我可以写一个简单的 switch/case 语句,但是如果条件改变或添加新的馅饼,维护就不容易了,所以......

我有点卡住了,真的不知道如何封装条件和决策以减少条件之间的耦合并允许在馅饼 cooking 条件下轻松维护。

您将如何处理复杂的决策算法实现?

最佳答案

I could write a simple switch/case statement, but the maintenance would not be easy if conditions change or new pies are added, and so...

I'm kinda stuck and really don't see how I could encapsulate the conditions and decision making to decrease couplign beetween conditions and to allow easy maintenance on the conditions of pie cooking.

How would you handle complexe decision making algorithm implementation?


从 switch/case 到可维护的 OOP 的经典更改/重构是用抽象类特化/实现替换每个条件和操作。
旧代码:
variable_t variable; // initialized elsewhere
switch(variable) {
case value1:
do_action1();
break;
case value2:
do_action2();
break;
// ...
}
新代码:
struct Actor // actor is your "abstract chef"
{
virtual ~Actor();
virtual bool matches(variable_t const v) const = 0;
virtual void do_action() = 0;
};
现在,对于每个 Action 和条件组合,您创建一个特化:
struct SweedishChef: public Actor {
bool matches(variable_t const v) const override
{
return v == 1;
}

void do_action() override
{
std::cerr << "bork! bork!\n";
}
};
有了这个,客户端代码不再有任何硬编码。
客户端代码的初始化:
std::vector<std::unique_ptr<Actor>> actors;
actors.emplace_back( new SweedishChef{} };
// adding a new type of chef simply means adding _one_ line of
// code here, for the new type
决策代码(替换旧的 switch代码):
// using std::find, begin, end
variable_t variable; // initialized elsewhere
const auto chef = find(begin(actors), end(actors),
[&v](const std::unique_ptr<Actor>& a) { return a->matches(v); });

if(chef != end(actors))
chef->do_action();
else
{
// here goes whatever was in the default part of the switch code
}
从维护和可测试性的角度来看,这段代码更易于维护:
  • 添加新厨师时对客户端代码的更改很小
  • 厨师和命令之间的交互已在界面后面正式化(并卡住)
  • 每个条件/ Action 都可以(并且应该)单独测试
  • 分派(dispatch)机制可以单独测试(并使用模拟注入(inject)的 actor,用于命中各种情况)。
  • 初始化机制可以单独测试
  • 关于c++ - 决策、复杂条件和规划易于维护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26096632/

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