Factory Design Pattern Example

Factory Design Pattern is used to centralizes all new object instantiation under 1 class, or in other words, having 1 class responsible for creating objects! The object created by Factory will use a common interface to be compatible with other related finer detail classes.

The objective of migrating creation responsibility is to prevent client class being exposed to many classes. Client class are the ones who uses these objects by instantiating them within itself. This posses a major risk where when a used class is removed or updated to a new name, the client class will crash unless updated to be in sync with them.

Imagine if there were 20 client classes using a class which frequently updates itself, you will need to re-update all 20 classes! The solution is to have an intermediary, such as a Factory Pattern to build those objects for the client. Those created objects will have a common interface (example: Weapon) for finer details (example: Sword, Bow, Axe, Polearm, Spear, Gun, Claw, Wand, Staff).

Before Implementing Factory Pattern

The code below shows a Client who couples to 4 weapon classes (sword, spear, bow and crossbow). Couples or coupling means having a relationship with another foreign class via instantiation or reference. If more classes were coupled between clients, it will multiply the coupling substantially.

As the example displayed above, 1 client has reference to 4 classes. 2 client makes it 8 (2 x 4 = 8). Now when the referenced classes increased to 6, you will have a total of 12 couplings (2 x 6 = 12). So how does this affects in software or game development? If 2 referenced class were to be updated/removed, those 2 clients have to be re-updated.

After Implementing Factory Pattern

Here is the code with Factory Pattern implemented. Noticed that both client A and B has instantiated a WeaponFactory to produce the weapons they need. They do not need to know the finer details of the weapon, but they get the weapon to be used. Similarly if you were purchasing a car, you drive it but not into manufacturing the car engine parts. As a user, you interact with the Car interface.

In the program above, each client is interacting with Weapon Interface, not the Sword, Bow, Crossbow and Spear directly. These creates a loose coupling between client and weapon class. Any changes made in Sword affects 1 class, which is the Factory class. Since all instantiation or changes are done in 1 class, its easier to do maintenance without crashing other client classes.

Quick Search: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

2 thoughts on “Factory Design Pattern Example

  1. Nalan

    Thank You for the simple explanation.

  2. Factory pattern advice seeker

    Good simple example. Well done.