决策设计模式的帮助

时间:2010-06-25 18:18:26

标签: design-patterns

我的情况是(伪代码):

Action a;
Object o;
if(objectIsPartOfGroup(o, "Group1"))
  a = treatCaseGroup1();
if(a != indecisive)
  return a;

if(objectIsPartOfGroup(o, "Group2"))
  a = treatCaseGroup2();
if(a != indecisive)
  return a;

if(objectIsPartOfGroup(o, "Group3"))
  a = treatCaseGroup3();
if(a != indecisive)
  return a;
.
.
.

我想知道是否有适用于这种情况的模式,所以我不必重复“if(a!=犹豫不决)返回a;”每一步后检查一下?我发现一遍又一遍地重复这段代码并不是很专业?它添加了大量的代码行,并没有任何帮助清晰度,因此我觉得很糟糕。

编辑:一个对象可以是group1和group2以及group3等的一部分...所以说一个对象是group1的一部分并且动作是犹豫不决的,因为它也是group2的一部分,它将被一次又一次地处理,直到所有团体都得到了治疗。最后,结果也可能是犹豫不决的!

感谢您的帮助!

戴夫

4 个答案:

答案 0 :(得分:3)

public Action determimeAction( Object o, List<String> groups ) {
    for ( String group : groups ) {
        if ( ( ( GroupI ) o ).isPartOf( group ) ) {
            Action a = ( ( GroupI ) o ).treatCaseGroup( group );
            if ( a != indecisive ) {  // could this be a.isDecicive()
                return a;
            }
        }
    }
    return null; // or whatever
}

public interface GroupI () {
    public Action treatCaseGroup( String group );   // is implemented to know which Action to get.
    public Boolean isPartOf( Stirng group ); // is implemented the same as your example just move the method to your object
}

public class GroupImpl implements GroupI {
    public Boolean isPartOf( Stirng group ) {
    }
    public Action treatCaseGroup( String group ) {
        // use if, case, factory, or Dep Inection to get the correct action.
    }
}

在不知道所有逻辑的情况下,这应该起作用。

答案 1 :(得分:2)

查看Visitor design pattern

本质上,访问者模式是关于在不同静态对象上执行不同操作而不将它们绑得太紧。

正确地重构您的代码,您只需执行以下操作:

o.treat();

答案 2 :(得分:0)

看看责任链。您分离出每个Treat方法的责任,设置一个命令链。每个命令都将尝试处理该对象。

看看这里: http://www.dofactory.com/net/chain-of-responsibility-design-pattern

答案 3 :(得分:-2)

这不是一种模式,它不是深入的任何东西(它只解析你所询问的特定事物),但这样的工作会不会有效?

Action a;
Object o;

while (a == indecisive)
{
    if(objectIsPartOfGroup(o, "Group1"))
        a = treatCaseGroup1();
    if(objectIsPartOfGroup(o, "Group2"))
        a = treatCaseGroup2();
    if(objectIsPartOfGroup(o, "Group3"))
        a = treatCaseGroup3();
 }

 return a