C# Factory Method Design Pattern (2024)

The Factory Method design pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. This pattern lets a class defer instantiation to subclasses.

Frequency of use:

C# Factory Method Design Pattern (1)

high

C# Factory Method Design Pattern (2)

C# Builder

C# Prototype


UML class diagram

A visualization of the classes and objects participating in this pattern.

C# Factory Method Design Pattern (3)

Participants

The classes and objects participating in this pattern include:

  • Product(Page)
    • defines the interface of objects the factory method creates
  • ConcreteProduct(SkillsPage, EducationPage, ExperiencePage)
    • implements the Product interface
  • Creator(Document)
    • declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
    • may call the factory method to create a Product object.
  • ConcreteCreator(Report, Resume)
    • overrides the factory method to return an instance of a ConcreteProduct.

Structural code in C#

This structural code demonstrates the Factory method offering great flexibility in creating different objects. The Abstract class may provide a default object, but each subclass can instantiate an extended version of the object.

copy

using System;namespace DoFactory.GangOfFour.Factory.Structural{ /// <summary> /// MainApp startup class for Structural /// Factory Method Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // An array of creators Creator[] creators = new Creator[2]; creators[0] = new ConcreteCreatorA(); creators[1] = new ConcreteCreatorB(); // Iterate over creators and create products foreach (Creator creator in creators) { Product product = creator.FactoryMethod(); Console.WriteLine("Created {0}", product.GetType().Name); } // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Product' abstract class /// </summary> abstract class Product { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class ConcreteProductA : Product { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class ConcreteProductB : Product { } /// <summary> /// The 'Creator' abstract class /// </summary> abstract class Creator { public abstract Product FactoryMethod(); } /// <summary> /// A 'ConcreteCreator' class /// </summary> class ConcreteCreatorA : Creator { public override Product FactoryMethod() { return new ConcreteProductA(); } } /// <summary> /// A 'ConcreteCreator' class /// </summary> class ConcreteCreatorB : Creator { public override Product FactoryMethod() { return new ConcreteProductB(); } }}
Output

Created ConcreteProductA
Created ConcreteProductB

Real-world code in C#

This real-world code demonstrates the Factory method offering flexibility in creating different documents. The derived Document classes Report and Resume instantiate extended versions of the Document class. Here, the Factory Method is called in the constructor of the Document base class.

copy

using System;using System.Collections.Generic;namespace DoFactory.GangOfFour.Factory.RealWorld{ /// <summary> /// MainApp startup class for Real-World /// Factory Method Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // Note: constructors call Factory Method Document[] documents = new Document[2]; documents[0] = new Resume(); documents[1] = new Report(); // Display document pages foreach (Document document in documents) { Console.WriteLine("\n" + document.GetType().Name + "--"); foreach (Page page in document.Pages) { Console.WriteLine(" " + page.GetType().Name); } } // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Product' abstract class /// </summary> abstract class Page { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class SkillsPage : Page { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class EducationPage : Page { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class ExperiencePage : Page { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class IntroductionPage : Page { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class ResultsPage : Page { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class ConclusionPage : Page { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class SummaryPage : Page { } /// <summary> /// A 'ConcreteProduct' class /// </summary> class BibliographyPage : Page { } /// <summary> /// The 'Creator' abstract class /// </summary> abstract class Document { private List<Page> _pages = new List<Page>(); // Constructor calls abstract Factory method public Document() { this.CreatePages(); } public List<Page> Pages { get { return _pages; } } // Factory Method public abstract void CreatePages(); } /// <summary> /// A 'ConcreteCreator' class /// </summary> class Resume : Document { // Factory Method implementation public override void CreatePages() { Pages.Add(new SkillsPage()); Pages.Add(new EducationPage()); Pages.Add(new ExperiencePage()); } } /// <summary> /// A 'ConcreteCreator' class /// </summary> class Report : Document { // Factory Method implementation public override void CreatePages() { Pages.Add(new IntroductionPage()); Pages.Add(new ResultsPage()); Pages.Add(new ConclusionPage()); Pages.Add(new SummaryPage()); Pages.Add(new BibliographyPage()); } }}
Output

Resume -------
SkillsPage
EducationPage
ExperiencePage

Report -------
IntroductionPage
ResultsPage
ConclusionPage
SummaryPage
BibliographyPage

.NET Optimized code in C#

The .NET optimized code demonstrates the same real-world situation as above but uses modern, built-in .NET features, such as, generics, reflection, LINQ, lambda functions, etc. You can find an example on our Singleton pattern page.

All other patterns (and much more) are available in our Dofactory .NET product.


Not only does Dofactory .NET cover the Gang of Four and Enterprise patterns, it also includes pattern architectures, low-code, and RAD (Rapid Application Development) techniques. Accelerate development to where you can write entire solutions in just 33 days!.

This unique package will change your developer lifestyle. Here's what is included:

#1 .NET Success Platform

Learn more...

  • 69 gang-of-four pattern projects
  • 46 head-first pattern projects
  • Fowler's enterprise patterns
  • Multi-tier patterns
  • Convention over configuration
  • Active Record and CQRS patterns
  • Repository and Unit-of-Work patterns
  • MVC, MVP, & MVVM patterns
  • REST patterns with Web API
  • SparkTM Rapid App Dev (RAD) data access
  • Complete Art Shop, Ecommerce App
  • Complete Analytics, Dashboard App
  • Complete Art Shop, Ecommerce App
  • Complete SaaS, Multi-Tenant App
  • Everything 100% source code

C# Builder

C# Prototype

Jack Poorte

Last updated on Sep 30, 2023


Feedback

Guides

  • C# Patterns Intro
  • Abstract Factory
  • Template Method
  • Singleton
  • Composite
  • Factory Method
  • Facade
  • Strategy
  • Decoratator
  • Proxy
  • Command
  • Observer

On this page

  • Summary
  • UML Diagram
  • Participants
  • Structural code in C#
  • Real-world code in C#
  • Optimized code in C#

The Factory Method design pattern is a creational pattern used to define an interface for creating objects but allows subclasses to determine the specific class instantiation. This empowers classes to delegate the instantiation process to their subclasses, promoting flexibility in object creation. It's highly utilized in software development due to its versatility.

Concepts Used in the Article:

Factory Method Pattern:

The pattern involves participants like Product (defines the object interface), ConcreteProduct (implements the Product interface), Creator (declares the factory method), and ConcreteCreator (overrides the factory method).

UML Class Diagram:

It's a visualization showcasing classes and objects involved in the Factory Method pattern. It illustrates relationships between Product, ConcreteProduct, Creator, and ConcreteCreator.

Structural Code in C#:

The code exemplifies the Factory Method's flexibility by demonstrating how an abstract class can offer a default object while allowing subclasses to instantiate extended versions.

Real-world Code in C#:

This section presents practical application scenarios of the Factory Method pattern. It showcases how Document classes like Report and Resume use the Factory Method in their constructors to instantiate extended versions of the Document class.

Optimized Code in C#:

This part refers to an updated approach in .NET, utilizing modern features like generics, reflection, LINQ, and lambda functions. Although the Factory Method isn't directly shown, it suggests employing contemporary .NET functionalities to optimize design patterns, akin to how the Singleton pattern is demonstrated elsewhere.

The provided snippets exhibit various facets of the Factory Method pattern. From structural representation in UML to practical implementations in C#, they illustrate its adaptability and usefulness in software design.

C# Factory Method Design Pattern (2024)
Top Articles
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 6319

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.