c++中查找兄弟节点的状态
c++ finding the state of a sibling
在我的代码中,有一个基类a,它有三个子类A1, A2, A3。这些对象有一个状态来指定它们是否处于活动状态。
现在在另一个类B中,创建了A1、A2和A3的对象。现在在B内部的函数中,
int B::SetState( A& aObj)
{
//if aObj is an instance of A1, do nothing and return.
//if aObj is an instance of A2, do something if A3 is active
//if aObj is an instance of A3, do something if A2 is active
//the code below i would like to change to something more maintainable
if ( aObj.GetNumber() == 0 )
return;
A& otherAObj = aObj.GetNumber()==1? GetAObj(2) : GetAObj(3);
if ( otherAObj.IsActive() )
{
//do something with aObj
}
}
我想将代码更改为类似aObj.DoSomething()的东西,但兄弟姐妹之间的依赖关系使其变得困难。还有其他好的重构方法吗?类结构必须保持不变。
你可以重构它:
if ( otherAObj.IsActive() )
{
//do something with aObj
}
输出到doSomething()函数
public class A{
virtual bool isActive(){ return false; }
virtual bool isPending(){ return false; }
virtual void doSomething()
{
if(true == isActive())
{
...
if(false == isPending())
{ ... }
...
}
};
}
public class A_State_Active : A
{
bool isActive(){ return true; }
}
public class A_State_Pending : A
{
bool isPending(){ return true; }
void doSomething()
{
throw new InvalidOperationException("Don't be messing");
}
}
或者甚至将doSomething的基本版本设置为纯虚的,以强制用户实现特定于状态的版本。
然而,你不应该在子类中实现任何基于不同对象状态的东西。在我看来,在这种情况下你应该使用管理器类型对象。如果真的想这样做,你应该把对其他对象的引用传递给doSomething()
函数,并根据传递对象状态的返回值修改运行时行为(使用"isActive"/"isPending"API进行查询)。
另一种选择是取消继承而支持组合。让A
是一个类,它持有对A_State
类的引用。然后子类化A_State
。
class A
{
//public functions
...
const A_State* getState(){ return m_poMyState; }
void setState(const A_State const * aStateObj ){ m_poMyState = aStateObj; }
}
您可以使用以下函数来增强A接口
virtual bool hasSibling() const = 0;
virual int siblingNumber() const = 0;
然后,在子类中给定合适的实现,B代码可以做:
if (!aObj.hasSibling()) return;
A & otherObj = GetAObj(aObj.siblingNumber());
if (otherObj.isActive()) { ... }
如果您可以将更多的逻辑推到A中(根据告知不询问原则)会更好,但是对于驻留在b中的GetAObj,这可能会很棘手。
相关文章:
- 反向给定链表中的K节点
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Boost Graph Library,修复节点大小
- C++A*算法并不总是在路径中具有目标节点
- 如何找到2个单链表的公共节点
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 为什么我的删除节点函数实际上没有删除节点?
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 我们可以删除链表中静态内存中的节点吗
- 如何在pugixml中获取节点的内部XML
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- OSX MetalKit CVMetalTextureCacheCreateTextureFromImage失败,状态:
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- std::future_error:无关联状态
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 检查两个节点在子节点上是否具有相同状态的更优雅的方法
- 从系统表中获取节点状态
- 添加节点时C++二叉搜索树状态访问冲突错误
- 为所有openvdb::Grid节点设置/取消设置活动状态
- c++中查找兄弟节点的状态