The classic book “Design Patterns: Elements of Reusable Object-Oriented Software” has 23 patterns. They are ordered by intent: creational, structural, and behavioral patterns. Today, I focus on the creational pattern Factory Method.
Five patterns in the book “Design Patterns: Elements of Reusable Object-Oriented Software” (short Design Patterns) are creational, seven structural, and the remaining one behavioral. First of all, what does this mean?
- Creational patterns deal with object creation in a well-defined way.
- Structural patterns provide mechanisms to organize class and objects for larger structures.
- Behavioral patterns deal with communication patterns between objects.
Before I start with the creational patterns, I want to make a short disclaimer.
I present about half of the 23 design patterns. For the remaining ones, I only provide a fact sheet. The selection of the presented design pattern is based on two points.
- Which patterns did I encounter most often as a software developer in the last twenty years?
- Which patterns are still in use?
My explanation of the presented design patterns is intentionally concise. My idea is to present the key principle of a pattern and present them from a C++ point of view. If you want to have more details, there is excellent documentation available. Here are a few choices:
- The classic: “Design Patterns: Elements of Reusable Object-Oriented Software“
- Nice introduction: “Head First Design Patterns”
- Wikipedia articles: Design Patterns
Creational patterns deal with object creation. Let’s dive deeper.
I will write about two of the five creational patterns: Factory Method and Singleton. I know, I know the Singleton could also be regarded as an Anti-Pattern. In a later post, I will discuss the Singleton in more depth. Let’s start with the Factory Method:
Here are the facts:
The factory method defines an interface to create a single object but lets subclasses decide which objects to create. The interface can provide a default implementation for creating objects.
Also known as
- A class does not know what kind of objects to create
- Subclasses decide what object to create
- Classes delegate the creation of objects to subclasses
Each container of the Standard Template Library has eight factory functions to generate various iterators.
cbegin: returns an iterator to the beginning of the container
end, cend: returns an iterator to the end of the container
rbegin, crbegin: returns a reverse iterator to the beginning of the container
rend, crend: returns a reverse iterator to the end of the container
c,return constant iterators.
- Objects created by
- Implements the interface
- Declares the factory method
- Calls the factory method
- Overwrites the factory method
The Creator does not instantiate the Concrete Product. It calls its virtual member function
factoryMethod. Consequentially, the Concrete Product is created by the Concrete Creator, and the object creation is independent of the Creator.
This pattern is also known as a virtual constructor.
- Abstract Factory is typically implemented using Factory Methods.
- Factory Methods are often steps of the Template Method.
Honestly, the name virtual constructor is misleading. We don’t have a virtual constructor in C++, but we have virtual construction to simulate a virtual constructor.
Assume you have a class hierarchy with an interface class
Window and two implementation classes,
Now, you want to create a new
Window based on an existing one. This means that when you put an instance
FancyWindow inside the factory function
getNewWindow, it should r
eturn an instance of the same class.
Classically, the factory method is implemented using an
enum and a factory function. Here is the first try:
The factory function in line (1) decides, based on the incoming
Window (lines 2 and 3) should be created. It uses window->getType() (line 4) to get the right
Window type. The
WindowType is an enumeration.
Finally, here is the output of the program:
Honestly, I don’t like this solution for the following reasons:
- When my application should support, I would have to extend the enumeration
WindowTypeand the switch statement.
- The switch statement becomes more and more difficult to maintain if I add new
- The code is too complicated. This is mainly due to the
Let me replace the switch statement with a virtual dispatch. Additionally, I also want to clone the existing
Window supports now two ways to create new ones: a default constructed
Window with the member function
create (line 1) and a copy constructed
Window with the member function
clone (line 2). The subtle difference is that the constructor takes the this pointer in the member function
clone. (line The factory functions
createWindow (line 3) and
cloneWindow (line 4) dispatch on the dynamic type.
The output of the program is promising. Both member functions
clone display the name of the object they create.
By the way. It is fine that the virtual member functions
clone member functions of the
DefaultWindow and the
private, because you use them via the
Window interface. In the interface, both
member function are
Am I’m done with the factory method? NO! The program
factoryMethod.cpp has two serious issues. ownership semantic and slicing. Let me write more about it in my next post.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,