Through the class name, reflection creates an instance of the class

  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>()

Guess you like

Origin blog.csdn.net/zhang8593/article/details/130640782