As object-oriented software has evolved over the years, quite a few solutions to specific problems have also adapted and gained wide adoption. In 1995, a book called “Design Patterns: Elements of Reusable Object-Oriented Software” documented 23 patterns and started a new way to describe software that would be understandable to other developers. This book was written by four authors, Erich Gamma, Richard Helm, Ralph Johnson, and John Glissades, who are often referred to as the Gang of Four. The book is also sometimes just referred to as the Gang of Four book or just the GoF book.
When you learn how to make use of these patterns, your software will become more flexible and easier to maintain as new features are added. This episode introduces patterns and then describes the factory pattern.
The code example given in the episode describes a base class called Dungeon that makes use of a base class called Monster. There can be different types of monsters just like there can be different types of dungeons. The base Dungeon class doesn’t know what specific Monster class to create so instead it declares a virtual method called createMonster. This method could have a default implementation or it could be pure virtual. That’s up to you.
The main thing is that a specific dungeon class, let’s say a MountainCave class that derives from Dungeon, overrides the createMonster method to create some specific instance that derives from the Monster class. By deriving from the Dungeon class, you can change the type of monster that gets created. This is the factory pattern. The createMonster method is called the factory method.