Factory Method Design Pattern – Object Oriented Design – C Sharp

The Factory Method design pattern in object oriented design is a way of creating objects, but letting subclasses decide exactly which class to instantiate. Various subclasses might implement the interface; the Factory Method instantiates the appropriate subclass based on information supplied by the client or extracted from the current state.

 

factory-method-design-pattern-uml-diagram

factory-method-design-pattern-uml-diagram

Factory Pattern

Interface IProduct

Class ProductA Implements IProduct

Class Creator

Class Client

Member Variables Member Variables Member Variables Member Variables
  Creator

IProduct initialized from FactoryMethod

 

Member Functions Member Functions Member Functions Member Functions
  IProduct FactoryMethod

 

Use it when
Use when
  • Flexibility is important.
  • Objects can be extended in subclasses
  • There is a specific reason why one subclass would be chosen over another—this logic forms part of the Factory Method.
  • A client delegates responsibilities to subclasses in parallel hierarchies.
Consider Using instead
  • The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).
  • The Prototype pattern to store a set of objects to clone from the abstract factory.

C Sharp Code for Factory Method Pattern

using System.Collections.Generic;
namespace FactoryMethod
{
    class MainApp
    {
        static void Main()
        {
            // Document constructors call Factory Method
            var documents = new List { new Resume()};
            // Display document pages
            foreach (var document in documents)
            {
                Console.WriteLine(document + "--");
                foreach (var page in document.Pages)
                {
                    Console.WriteLine(" " + page);
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
    abstract class Page
    {
        public override string ToString()
        {
            return this.GetType().Name;
        }
    }
    class SkillsPage : Page
    {
    }
    class EducationPage : Page
    {
    }
	class ExperiencePage : Page
    {
    }
    abstract class Document
    {
        public Document()
        {
            this.CreatePages();
        }
		public List Pages { get; protected set; }
		public abstract void CreatePages();
		public override string ToString()
        {
            return this.GetType().Name;
        }
    }
    class Resume : Document
    {
        // Factory Method implementation
        public override void CreatePages()
        {
            Pages = new List
              { new SkillsPage(), 
                new EducationPage(), 
                new ExperiencePage() };
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *