algorithm - 猛击阀模式

标签 algorithm design-patterns language-agnostic

在过去的几十年里,我看到过很多次的事情是 slam valve type code,其中有一个人为的值,一旦某个值被破坏或许多迭代已经过去。

对您来说有点抽象?

一些具体的例子:

文件读取

在这种情况下,数据工厂中的文件在夜间被读取,因此需要在特定时间之前进行处理,以便系统在早上可用。注意文件是否完成并不重要。

int linesRead = 0;

const int SillyAmount = 1000000;

while (!EOF)
{
    text = ReadLine();
    // Do Some complicated processing with the text
    linesRead++;

    if (linesRead > SillyAmount)
        break;
}

服务对话

在此示例中,对象通过服务调用逐渐增强,直到数据足够好以供稍后处理。

int conversationLines = 10;

while (conversationLines > 0 && conversation.Status != Complete)
{
    conversation.Next();
    // Process conversation
    conversationLines--;    
}

问题。

(1) 这种东西有没有设计模式之类的?

(2) 如果没有 (1) 并且假设您是人为地退出循环,这可以被视为代码异味吗?

最佳答案

你的第一个例子可以这样写:

int linesRead = 0;
const int SillyAmount = 1000000;

do {
  text = ReadLine();
  // text processing
} while (!EOF && ++linesRead <= SillyAmount);

这看起来不再像 hack 了(没有 break)。没有想到这个模式。

第二个留给更多的解释(需要一个更完整的例子才能真正说明)。我们可以争辩说对话对象也许应该设计为 state machine。 (另请参阅 state pattern )并在内部处理对话以防止此类代码公开。要完成的实际处理可以作为(减少?)函数传递,或使用某种 strategy pattern实现取决于预定义的对话类型。有很多方法可以重新排列它。我们需要一个更现实的例子,因为这个例子有点奇怪(对话有迭代器 (conversation.Next();) 但行数在外面......可以告诉它最多处理一定数量 conversation.processUpTo(10);?)。

关于algorithm - 猛击阀模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28875636/

相关文章:

Java关于实现方法中运行时类型检查的问题

algorithm - NLP语法: fixing a to an?

algorithm - 在多个最短路径之间具有选择标准的有向未加权图中的最短路径?

algorithm - 符号 a (mod b, n) 是什么意思?

java - 查找数字的所有排列的算法

javascript - 如何遍历由二维数组表示的板上单元格的所有邻居?

algorithm - 分类法中两个概念的最低上级

objective-c - 没有协议(protocol)的 iOS 委托(delegate)?

java - 工厂方法实现

algorithm - 指数循环