Game Programming Patterns: The Factory Method by Example

digitsensitive
2 min readAug 5, 2020

--

Photo by Ant Rozetsky on Unsplash

In this article we will explore the creational pattern called Factory Method (also called Virtual Constructor). The Factory Method is one of the Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides) design patterns.

Let’s start this article with a very simple example:

We just created a Simple Factory! With it’s creational function create() it is capable of receiving an enemy type as string, create the requested enemy type and return it. It is obvious that you will need a base enemy class and the different enemy types as separate classes who extend from the base enemy class.

If you make the create function static, you can access it directly with: SimpleEnemyFactory.create(…)!

Remember that this example showed the Simple factory pattern and not the Factory method pattern! I just thought it might be a good start for this article. Let’s have a look at the Factory method pattern now.

What is the Factory method pattern?

Imagine that you own a pizza place. You offer different kind of pizzas, each with a unique set of ingredients. If you call the Prosciutto Factory, you do not care about which ingredients are necessary. You just want to get a Prosciutto. That is exactly what this example shows.

Later you might want to create own classes Prosciutto and Margherita who extend a base class Pizza. You would move the implementation into the constructor of the corresponding class.

You will be more flexible in the future. It is simple to add a new pizza and it won’t break the whole code. If at any time a recipe changes, you just need to adapt the implementation at one place and everything will be updated.

When should I use the Factory method pattern?

Generally it is used in situations where you want to abstract the creation of an object away from its implementation. Mostly in situations, where the implementation (= logic) is complex.

Example

You can find a simple example on my Github repository, where I use Phaser 3 with TypeScript.

References

--

--