【问题标题】:Generic empty overloaded constructor and when not to use generics泛型空重载构造函数以及何时不使用泛型
【发布时间】:2013-10-24 20:58:03
【问题描述】:

我目前正在构建一个通用状态机,并且我正在使用带有通用参数的StateMachine 的构造函数来设置创建时的回退状态,以防机器无事可做。

我想知道拥有两个构造函数是否是不好的做法,一个在需要创建新状态对象时由状态机本身使用,另一个在第一次初始化状态机时使用(设置默认值)后备状态)。

我最大的问题是:我是否在滥用泛型,有没有时候不应该使用泛型?

状态机创建:

//The generic parameter is the default "fallback" state.
_nodeStateMachine = new NodeStateMachine<IdleNodeState>();

状态机构造函数:

public NodeStateMachine()
{
    _currentState = new T();
}

以下是NodeStateMachine 类中状态的更改方式:

public void ChangeState<U>() where U : INodeState, new()
{
    _nextState = new U();
}

有问题的构造函数直接位于状态本身:

public NullNodeState(){} // To use the class generically.

public NullNodeState(ConditionCheck check)
{
    _nullCheck = check;   
}

【问题讨论】:

    标签: c# generics interface state null-object-pattern


    【解决方案1】:

    我看不出状态机是如何通用的,因为它似乎唯一的限制是状态实现INodeState。在这种情况下,我会创建一个指定初始状态的静态工厂方法:

    public class NodeStateMachine
    {
        private INodeState _nextState;
        private NodeStateMachine(INodeState initial)
        {
            _nextState = initial;
        }
    
        public void ChangeState<U>() where U : INodeState, new()
        {
            _nextState = new U();
        }
    
        public static NodeStateMachine Create<T>() where T : INodeState, new()
        {
            return new NodeStateMachine(new T());
        }
    
        public static NodeStateMachine Create(INodeState initial)
        {
            return new NodeStateMachine(initial);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多