Factory Pattern without a Switch or If/Then

前端 未结 4 1714
离开以前
离开以前 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 14:51

    You could make use of custom attributes and reflection.

    [PositionType(1)]
    class Manager : Position
    {
        public override string Title
        {
            get
            { return "Manager"; }
        }
    }
    
    [PositionType(2)]
    class Clerk : Position
    {
        public override string Title
        {
            get
            { return "Clerk"; }
        }
    }
    

    In your factory you could then get all classes that inherit from Position and find the one that has the PositionType attribute with the correct value.

    static class Factory
    {
        public static Position Get(int id)
        {
            var types = typeof(Position).Assembly.GetTypes()
                .Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Position)))
                .ToList();
    
            Position position = null;
            foreach(var type in types)
            {
               type.GetCustomAttributes();
    
               if(type.PositionId == id)
               {
                   position = Activator.CreateInstance(type) as Position;
                   break;
               }
            }
    
            if(position == null)
            {
                var message = $"Could not find a Position to create for id {id}.";
                throw new NotSupportedException(message);
            }
    
            return position;
        }
    }
    

提交回复
热议问题