Factory method
Essential design patterns for all software engineering levels.
In my next series of posts, I’ll be covering some of my favorite software design patterns that will serve you well at all levels of your software engineering career.
Design patterns
As your software system evolves and grows you’ll start to encounter problems with the organization and design of your code. It’s likely that the problems you encounter have reusable solutions.
In software engineering, these are called software design patterns.
It’s worth learning about these patterns and taking time to develop your skills to be able to recognize and apply them. They make you a more productive coder. Design patterns empower your ability to communicate ideas about software efficiently with your team.
Plug (affiliate links)
There’s no shortage of content on design patterns and there’s plenty of material freely available online. If you like books, the classic reference text, published in 1994, Design Patterns: Elements of Reusable Object-Oriented Software, written by the Gang of Four, is a great place to start. Head First Design Patterns, is a good alternative if find the original design patterns book too dry. If you’ve got more experience under your belt, I’d recommend Patterns of Enterprise Application Architecture and Enterprise Integration Patterns.
From my own experience, here is one of my favorite patterns.
Factory method pattern
You write code to create objects a lot.
A pattern I frequently use to create objects is the Factory method.
There are more complex patterns to deal with the problem of object creation, Factory and Abstract Factory, those are more useful when you have logic associated with your object creation or a group of factories with a common theme.
The factory method is simple and straightforward. Let’s take a look.
The factory method pattern deals with the problem of creating objects without specifying the exact class by encapsulating it inside a function.
Let’s dive into a practical example, using React JS.
I have some JSON data that I would like to create into html views.
Right now I have two style requirements, table and list, but my product and design team told me I’ll need to support a grid and carousel view next sprint…
I can use a factory method to encapsulate the exact views that are instantiated for a given view style.
Because the client code will use the factory, it makes swapping out the underlying components or html elements easy. I can add the grid and carousel views to my factory next sprint without having to change my clients.
Happy coding!