Skip to main content

C# Generic Factory

Implement Factory pattern using generics


   public interface IDoWork
  {
      string DoWork();
  }

    Declare an Interface first by abstracting the common  functionality
   Here I am taking the example of DoWork

   public class Manager : IDoWork
  {
    public string DoWork()
    {
        return "Manager Manages School";
    }
  }

    Implement the IDoWork in concrete classes as shown 

    public class Teacher : IDoWork
    {
        public string DoWork()
        {
            return "Teacher teaches student in school";
        }
    }

    public class Student : IDoWork
    {
        public string DoWork()
        {
            return "Study in school";
        }
    }

This class will actually create an instance of the concrete class so that you can work on that        object further

    public class FactoryDemo
    {
        public T CreateFactroy<T>() where T : class
        {
            var type = typeof(T);
            return Activator.CreateInstance(type) as T;
        }
    }

In client you can test as shown below

         static void Main(string[] args)
        {
            //bool isWindows = true;
            //var res = DBConnect(isWindows);
            //Console.WriteLine(" Connection - " + res.ToString());
            FactoryDemo create = new FactoryDemo();
            IDoWork obj = create.CreateFactroy<Teacher>();
            Console.WriteLine(obj.DoWork());

            obj = create.CreateFactroy<Student>();
            Console.WriteLine(obj.DoWork());

            obj = create.CreateFactroy<Manager>();
            Console.WriteLine(obj.DoWork());

            Console.ReadLine();
        }

Comments

  1. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.. dot net training and placement in chennai | best dot net training in chennai

    ReplyDelete
  2. After exploring a handful of the articles on your website, I seriously like your way of writing a blog. I bookmarked it to my bookmark site list and will be checking back in the near future. Take a look at my web site too and let me know how you feel.
    Click here to get More information.

    ReplyDelete
  3. This is an awesome post.Really very informative and creative contents about Java. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.


    Java training in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Online Training

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete

Post a Comment