Factory Design Pattern in Swift for Beginners

The Ford assembly line in 1913 by Wikimedia

What is Factory Design Pattern?

  1. The owner of the factory that uses/owns the creation methods
  2. The factory that creates the end object
  3. The object that is the created end product
Factory design pattern diagram

When do we use it?

  • You create objects from the same models over and over again,
  • Not only creating a particular object but different flavors of the same model according to properties,
  • Overall simplifying an object creation,
  • Streamlining object creation in projects such as UI components,
  • Needing the ability to change all objects all over the project,
  • Reducing the if/switch statements inside the view controller.
Before implementing the factory pattern


Define the models, Score and ScoreCard
  1. The first one is the Score which we define it with an Int point. And it also provides us with a computed property status. The status property will come in handy when differentiating between scores. We won't be dealing with math in the factory method, because it's taken care of here.
  2. The other is ScoreCard which we will fill with the information given by the Score model.
Create the factory class
  1. Now we created the ScoreCardFactory class.
  2. It has one method for now which takes a Score argument and returns a ScoreCard.
  3. Inside the createScoreCard method, we create the ScoreCard object according to the status of the score using the switch case.
  1. We defined some scores.
  2. Initialized the ScoreCardFactory.
  3. Created ScoreCards using the factory's createScoreCard(for:) method.
  4. Printed the result.

A real-world case

Be careful when…



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store