- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试找到一种优雅的方式来实现易于维护的决策算法,因为决策的条件可能经常变化。
我将尝试更具体地举一个例子:
假设我正在尝试管理一家餐厅厨房的 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?
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
}
从维护和可测试性的角度来看,这段代码更易于维护:
关于c++ - 决策、复杂条件和规划易于维护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26096632/
p { font-family: "Comic Sans",sans-serif; } #div1 { width: 7.5%; height: 100px;
我很快就会在费城的 Code Camp 上发表关于持续集成的演讲。我没有熔岩灯、环境球或其他任何东西的经验 - 但我认为这将是对演示的一个很好的补充,激发热情。 任何人都可以推荐一款非常易于设置/使用
我是一名优秀的程序员,十分优秀!