public class LightStateFactory
{
private static readonly IDictionary<Type, TrafficLightState> _lightStates
= new Dictionary<Type, TrafficLightState>();
private static readonly object _locker = new object();
public static TrafficLightState GetLightState<T>() where T : TrafficLightState
{
Type type = typeof(T);
if (!_lightStates.ContainsKey(type))
{
lock (_locker)
{
if (!_lightStates.ContainsKey(type))
{
TrafficLightState typeface = Activator.CreateInstance(typeof(T)) as TrafficLightState;
_lightStates.Add(type, typeface);
}
}
}
return _lightStates[type];
}
}
transfer:
LightStateFactory.GetLightState<GreenState>()