仅当对象处于特定状态时,操作才有效

Operations are valid only if object is in particular state

本文关键字:操作 有效 状态 对象 于特定      更新时间:2023-10-16

我的应用程序中有很多类型的对象。所有状态都可以具有以下状态:UpToDate,OutOfDate,NotComputed。仅当对象的状态为 UpToDate 时,才允许对象的所有操作。如果对象的状态为 NotComputed 或 OutOfDate,则唯一允许的操作是 Compute 和 ChangeComputingParams。在 gui 中,我想仅在允许的情况下显示对对象的操作。所以我有操作验证器对象,对于返回对象上的操作是否应显示在 gui 上的每个对象。问题是,每次我向某个对象添加新操作时,我都需要转到它的 OperationValidator 类,并在那里添加新函数。这一定是更好的方法。例:

class Object1OperationValidator
{
    Object1OperationValidator(Object1& object1)
    {
       mObject1 = object1;
    }
    bool CanDoCompute()
    {
       return true;
    }
    bool CanDoChangeComputationParams()
    {
       return true;
    }
    bool CanDoOperation1()
    {
       if(mObject1.State() != UpToDate )
          return false;
       else
          return true;        
    }
    .....
    bool CanDoOperationN()
    {
        if(mObject1.State() != UpToDate )
          return false;
       else
          return true;
    }
 }

您可以将模板化类与验证函数的实现一起使用:

template <class T>
void CheckBaseOperations
{
public:
    CheckBaseOperations(T * obj)
        :inst(obj)
    {}
    bool CheckOperation()
    {
        //...
        return inst->State() != X;
    }
public:
    T * inst;
};
//----------------------------------------------------------------------
//for generic types
template <class T>
void CheckOperations : public CheckBaseOperations<T>
{
public:
    CheckOperations(T * obj)
        :CheckBaseOperations<T>(obj)
    {}
};
//----------------------------------------------------------------------
template <> //specific validation for a certain type.
void CheckOperations <YourType> : public CheckBaseOperations<YourType>
{
public:
    CheckOperations(YourType * obj)
        :CheckBaseOperations<YourType>(obj)
    {}
    bool CheckOperationForYourType()
    {
        //...
        return inst->State() != X;
    }
};

如果需要,您还可以拥有专门针对特定类型的CheckOperations