這裏有一種方法可以與Autofac 2.2(http://autofac.org)來完成:
首先,枚舉狀態(使一些可能值)來區分:
public enum DeviceState { Online, Offline }
然後,狀態的實現,如:
public class OnlineState : IDeviceState { }
接下來,註冊每個狀態與其相應的枚舉項:
var builder = new ContainerBuilder();
builder.RegisterType<OnlineState>().Keyed<IDeviceState>(DeviceState.Online);
builder.RegisterType<OfflineState>().Keyed<IDeviceState>(DeviceState.Offline);
// Register other components here
最後,硬件設備使用索引來選擇狀態。 IIndex
的實現由容器自動提供:
public class Modem : IHardwareDevice
{
IIndex<DeviceState, IDeviceState> _states;
IDeviceState _currentState;
public Modem(IIndex<DeviceState, IDeviceState> states)
{
_states = states;
SwitchOn();
}
void SwitchOn()
{
_currentState = _states[DeviceState.Online];
}
}
希望這會有所幫助。
尼克
你的意思是「我希望國家是由IoC容器創建的」? – 2010-08-14 05:50:15
這意味着我需要State對象可能必須由IoC容器滿足的任何依賴關係,而不是讓Factory實例化它們並將它們傳遞給State對象。 – Darran 2010-08-14 11:24:33