Design Patterns — Creational Patterns — Factory Pattern in Swift

As a budding computer scientist, you no doubt have heard of design patterns in your classes and learning paths. Design patterns are blueprints which outline the best practices that create re-usable object oriented code, solving common software problems. To avoid giving you a long history lesson, I will describe the origin of design patterns as dating back to the 1970s but gaining wide acceptance with the release of Design Patterns: Elements of Reusable Object-Oriented Software, published in 1994 and authored by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, collectively referred to as the Gang of Four (GoF). The book was wildly successful due to its description of 23 classic software design patterns. Design patterns are extremely useful for helping you break down complex systems into components that very often, fit into one of the design patterns described by the GoF. Because I know, as developers, we love to learn and sometimes need quick references to do our jobs better, I’m dedicating time to write a series of articles, of which this is the first, to show how to use each GoF design pattern in Swift.

It’s common to group the design patterns we will cover into several related categories: creational patterns, structural patterns, and behavioral patterns. For the remainder of this article, we are going to focus on the Creational patterns and cover our first pattern: the Factory pattern.

Creational Pattern: Factory Pattern

Creational patterns are all about ways to remove the complexities involved with creating objects. The factory pattern is a way to encapsulate the implementation details of creating objects, which adheres to a common base class or interface. The factory pattern allows the client that receives the created object to use the object return via the common interface without caring about the type of concrete object that is actually created.

The factory pattern separates the implementation details of creating objects from the common interface that allows users to generically use the object. Let’s consider an example to make this idea more concrete.

Imagine that you run a head hunter firm that sources all of its leads from various job boards. For each job board, you collect the contact details and resumes for potential “targets”. I mean job seekers. Once you have the contact info, you categorize them and send out boilerplate emails to each contact telling the prospect about potential matches you have for them. You want to automate the process because you connect hundreds of prospects every week. You’re essentially just “dialing for dollars,” so the more prospects you can process, the greater your chances of placing a prospect into a position, and the greater likelihood you’ll get paid. We can and will solve this problem using the factory pattern to handle the creation of the email templates.

I’m going to use a Swift Playground to show one way in which we could use the factory pattern to achieve our goal. You can find the playground file I used for this post here. To simplify things, let’s assume that each contact will have personal details along with the type of role they are seeking.

First, we will create the interface (or rather, protocol) that we will use to send our customized emails to our potential clients with information on the type of job they are seeking.

Let’s also add a struct for the Contact object.

Next, we will create several template objects that adhere to the JobContacterProtocol. We need templates to send to mobile developers, web developers, QA/ Testing, and product owners. We want to hide the details of these objects from clients and only expose the interface for use. What makes this pattern really useful is that each class is in charge of its implementation and can do anything as long as it adheres to the protocol. It can be used in a generic way by a client that only knows about the protocol.

Our next step is to create the actual factory that our client will use to get a concrete object that adheres to our protocol. The factory object in our case has just one method to return the job seeker object that adheres to the JobContacterProtocol based on a contact object that is passed in as a parameter to the function.

Our factory hides the need to know the type of object created because we will use our interface methods when we want to do anything with the created object. The added benefit of doing this is that we can add, change, or remove concrete objects from our factory without changing our client code!

In our example, we can create several contacts that we want to reach out to with opportunities. We can then contact these prospects with our exposed interface and cutdown our processing time with automation!

That’s it! Our factory example is complete. We can now send customized emails to our contacts based on the type of job they are seeking. We could expand on our example as our needs change and not have to change code that our client uses as long as our interface doesn’t change. That means we could add new jobs and job seeker objects to send customized emails to new contact types with no change to the client that uses our JobContactProtocol. We could also change the logic for creating our template, since that would only encompass an implementation change.

Wrapping Up

The factory pattern makes it possible for us to hide the implementation details for creating objects by allowing our clients to rely solely on a common interface for interacting with our objects. This allows us to remove unnecessary complexities involved with creating objects that have similar behavioral needs. The factory pattern also promotes separation and abstraction which both lead to reusable code that is easier to maintain. You can find the playground file for this article here.

On a lighter note, I also wrote an article on why creating native apps is probably the best way to go in most of your mobile development endeavors. Read it and weigh in the discussion!

As I mentioned, I will be completing a series on design patterns. You can read the next article on the Decorator Pattern in the article link below.

If you find this post helpful, please recommend it for others to read. If you’re looking to learn more about what’s new in Swift 3, I would encourage you to check out my new book Swift 3 New Features. Thanks!