2013-10-24 125 views
3

我目前正在建立一個通用的狀態機,我使用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; 
} 

回答

3

我沒有看到狀態機如何是通用的,因爲它似乎唯一的限制是各國執行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); 
    } 
}