The factory method pattern  deals with the problem of creating objects without specifying the exact class of object that will be created.

image

The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify the derived type  that will be created.

More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.

Code examples (click to enlarge/collapse):

The real world example is my favourite example using a Namer factory class. Depending on how you provide your full name (First-Name-First or Last-Name-First) your first name and last name are extracted from your full name. Using this pattern you can easily add other name patterns, for example how to handle middle names.

With this foundation you should be able to successfully implement the Factory Method Pattern.

This post is part of my series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern and look at simplified real-world C# code that implements the pattern.