In this series I’m going to be talking extensively about design patterns. More specifically, the 23 design patterns outlined in the book commonly referred to as “The Gang of Four”. In reality “The Gang of Four” refers to the four authors who created the book “Design Patterns: Elements of Reusable Object-Oriented Software”.
Now you may be asking yourself, what the hell is a design pattern anyway? To quote Wikipedia “In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design.” Simply put, a design pattern is a description or a template for how to solve a problem that can be used in many different situations.
There are three broad categories of design patterns. These are Creational Patterns, Structural Patterns, and Behavioral Patterns. In this article we’ll take a look at the first of the Creational design patterns, the “Abstract Factory” pattern.
An Abstract Factory creates objects that are related by a common theme. A concrete example will be provided shortly. Some issues this pattern comes to solve are:
- How can an application be independent of how its objects are created?
- How can a class be independent of how the objects it requires are created?
- How can families of related or dependent objects be created?
Mull those points over for a bit and really think about them. Without this pattern, we could technically create the objects directly in the class that needs them. The issue with that is the class now becomes inflexible because we are now committed to a certain type of object. This makes changing the implementation impossible without having to change the class.
DressClothesFactory and a
CasualClothesFactory. Each factory would have a
getShoes, getShirt, getPants method which would return the correct type of clothing (either dress, or casual).
Now you may be wondering, why do we need to wrap the creation logic in a factory, why not just create a new instance of the correct class (e.g.
new DressShoe()). A reason for this would be because the constructor function is not aware of the business logic in the global application. Using a factory method allows for caching and other complex logic that could decide on the creation of a
Now for a code sample:
Now for some pros and cons for this pattern.
- Avoiding tight coupling between classes and client code
- Single responsibility principle is adhered to
- Since the factories and classes must adhere to an interface, you can be sure the classes are compatible with each other
- Using this pattern with simple implementations can make the code more complex than strictly necessary.
That’s all for this one. In the next article we’ll talk about the Builder pattern.