Abstract Factory, Factory Method VS Reflection

Abstract Factory, Factory Method VS Reflection

Since abstract factory and factory method patterns belongs to creational patterns category by "Gang of Four". But there is a fundamental problems with both of these patterns. we need to use if / else or switch statements, But then later we can replace if / else or switch statements with Dictionary data structure in order to create objects of inherited classes. Please see the following code.

 public abstract class ModelBase  {
        
        private Lazy<Dictionary<string, ModelBase>> _modelBase = null;
        
        private Dictionary<string, ModelBase> Initialize()
        {
            return new Dictionary<string, ModelBase>(){
                {"City", new City() },
                {"Country", new Country()},
                {"Currency", new  Currency() },
                {"Label", new Label() },
                {"Language", new Language() },
                {"LanguageLabel", new LanguageLabel() },
                {"Market", new Market() }
            };

        }

        public ModelBase GetTable(string key)
        {
              _ModelBase = new Lazy<Dictionary<string, ModelBase>>(Initialize);

              return _ModelBase.Value[key];

        }
}

In the above code, I have used dictionary data structure in order to replace if / else and switch statement. All the classes mentioned in dictionary are inherited from base class, ModelBase. The method GetTable(string key) is returning the required object based on parameter "key". But still when we lazy load the dictionary, at that specific time, all the objects of derive classes will get instantiated. GetTable method will return one object based on "key" parameter.

On the contrary if we use Reflection then we can save this extra cost associated with instantiation of all derive objects as well as extra lines of code.

 public abstract class ModelBase
    {
    
       public ModelBase GetTable(string key)
        {
            ModelBase entity = Activator.CreateInstance(Type.GetType(key)) as ModelBase;

            return entity;
        }
  }

Check the code now, its only 2 lines of code and we are taking advantage of Reflection to instantiate the object of derive classes. The real trick is in "key" parameter of GetTable method. this "key" parameter is the name of class that we are going to instantiate. I know that reflection comes with a little performance crunch but in today's age of super fast computing it does not really matters :).

This is still an Abstract Factory and Factory Method patterns but with the power of reflection we have minimized the lines of code required with If / else, switch or Dictionary.

This is just an idea, your comments are highly appreciated.

Happy Programming :)

I have a question here, if at all we have to use reflection why can't we decorate the base classes/interfaces with attributes and get the corresponding child class object via that. Why we need factory in such case?

Like
Reply

If you are using parameterless constructor, it can be usefull yet many of the class usually use injection so you need to inject required objects. Thanks for sharing though

Like
Reply

Using reflection is good thought. But when your framework is responsible to create n number of objects. I would reconsider using reflection as it costs performance of the code. Rather lamda Expression tree can be used to create objects faster.

Like
Reply

Very clever. I like It!

Like
Reply

To view or add a comment, sign in

More articles by Eman Ali Mughal

Others also viewed

Explore content categories