4 Creating items with the Factory Method pattern
This chapter covers
- Pros and cons of the Factory Method pattern
- Creating a product interface and concrete products
- Building different creator class and factory method variations
- Scaling factories with Reflection and LINQ
- Integrating Unity prefabs to product and creator classes
In the last chapter, we built an enemy spawning system using the Prototype design pattern, Unity prefabs, and C# generics. In this chapter, we’ll learn about how the Factory Method design pattern lets you specify a common interface for objects you want to create, but let’s the subclass decide the actual class that gets instantiated. This scenario is common in games when you need an assembly-line process for creating and managing items, NPCs, or any objects you want to treat the same while deferring the type that gets created.
There are two related design patterns when it comes to factories: the Factory Method and Abstract Factory. The Factory Method pattern allows you to make objects without specifying the exact class that gets constructed, while the Abstract Factory pattern combines groups of related factories without specifying the concrete factory classes.