Design Patterns Bytes: Abstract Factory
Design Pattern Bytes is a series on exploring various software design patterns in easily digestible format. In this lesson, we will explore the Abstract Factory design pattern.
The Abstract Factory design pattern provides an interface for creating a collection or family of related objects. Instead of having a driver class specify a bunch of concrete classes for different cases, it uses a factory which abstracts the creation of these concrete objects. Changing a set of classes for different cases then becomes a cake walk: clients would only have to change the concrete instance of the factory in the place where it was instantiated.
If you have a program that creates different types of robots, for example, you could you have a structure like the following:
A client creates an instance of an AbstractRobotFactory, in the form of a KillerRobotFactory or a CleanerRobotFactory. Each concrete implementation of the factory provides factory methods which would create the concrete parts needed by the client, in this case, an AbstractRobotHead and an AbstractRobotBody. The client only needs to change which factory to instantiate to create the different types of robots.
The purpose of the Abstract Factory design pattern is to make it easy to create a family of objects without giving the client the responsibility to instantiate and orchestrate all of the related concrete classes in different places. In our example, this ensures that if the client needs a CleanerRobot, it wouldn’t accidentally create a robot with a CleanerRobotHead and a KillerRobotBody. What a mess that would be.
Hey! Thank you for taking the time to read this article. I’d love to hear your thoughts. Please leave a comment, heart, clap, and follow. For more, check out my website.
See you next time!