What Are Design Patterns?
Software design patterns are common solutions to problems which are regularly encountered in programming. These particular patterns deal with object-oriented programming exclusively, so applying these patterns to, say, a functional environment is a thoroughly bad idea. Some pattern proponents even go so far as to say that, in the object-oriented world, these design patterns are fullfledged best practices, though I often stop short of such an assertion.
The patterns I’ll be describing in this series originate from a book titled, appropriately enough, Design Patterns – Elements of Reusable Object-Oriented Software, written by a group of authors who have come to be known as the Gang of Four (GoF). These authors are Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. The original book was released in 1995, but despite what you may think it didn’t really create new patterns so much as give names to ones that already occurred naturally, so to speak.
That said, given that the examples in the book were given in C++ and Smalltalk, I thought I personally would be better served by having examples in modern C#, so that’s what my examples will be written in.
As the Gang of Four note in their book, there are three types of design patterns:
- Creational patterns deal with the creation of objects and instances.
- Structural patterns deal with the structure of classes and code.
- Behavioral patterns deal with the behavior of objects.
So, without further ado, turn the page to begin your journey with Design Patterns by learning about one of the most common Creational patterns: Factory Method!
What Is This Pattern?
The Factory Method design pattern is a Creational design pattern which defines an interface for creating an object, but doesn’t specify what objects the individual implementations of that interface will instantiate.
All that means is that when using this pattern, you can define certain methods and properties of object that will be common to all objects created using the Factory Method, but let the individual Factory Methods define what specific objects they will instantiate.
The Rundown
- Type: Creational
- Useful? 5/5 (Extremely)
- Good For: Creating objects in a related family.
- Example Code: On GitHub
- Blog Post: “Factory Method – The Daily Design Pattern”
The Participants
- The Product defines the interfaces of objects that the factory method will create.
- The ConcreteProduct objects implement the Product interface.
- The Creator declares the factory method, which returns an object of type Product. The Creator can also define a default implementation of the factory method, though we will not see that in the below example.
- The ConcreteCreator objects override the factory method to return an instance of a Concrete Product.