Factory Pattern without a Switch or If/Then

前端 未结 4 1715
离开以前
离开以前 2021-01-30 14:29

I\'m looking for a simple example of how to implement a factory class, but without the use of a Switch or an If-Then statement. All the examples I can find use one. F

4条回答
  •  天命终不由人
    2021-01-30 15:01

    public class PositionFactory
    {
        private Dictionary _positions;
    
        public PositionFactory()
        {
            _positions = new Dictionary();
        }
    
        public void RegisterPosition(int id) where PositionType : Position
        {
            _positions.Add(id, typeof(PositionType));
        }
    
        public Position Get(int id)
        {
            return (Position) Activator.CreateInstance(_positions[id]);
        }
    }
    

    Used like this:

                var factory = new PositionFactory();
                factory.RegisterPosition(0);
                factory.RegisterPosition(1);
    
                Position p = factory.Get(0); //Returns a new Manager instance
    

提交回复
热议问题