Creational Design Pattern: Factory Method

Ezra Lazuardy
Oct 17 · 8 min read

In the last post of my creational design pattern series, I’ve described the singleton pattern:

Now, let’s talk about the factory method pattern.

The factory method is a creational design pattern that provides an interface for creating an object in the superclass but allows subclasses to alter the type of object that will be created.

In a simple word,

A factory method is used to create multiple object types in a single interface.

Why use Factory Method?

As I said earlier, this pattern is used to create multiple object types in just a single interface. But what does it mean?. Before that, please take a look at the sample problem below.

Imagine that you’re creating a logistics management application. The first version of your app can only handle transportation by trucks, so the bulk of your code lives inside the class.

After a while, your app becomes pretty popular. Each day you receive dozens of requests from sea transportation companies to incorporate sea logistics into the app.

Adding a new class to the program isn’t that simple if the rest of the code is already coupled to existing classes.

Great news, right? But how about the code? At present, most of your code is coupled to the class. Adding into the app would require making changes to the entire codebase. Moreover, if later you decide to add another type of transportation to the app, you will probably need to make all of these changes again.

As a result, you will end up with pretty nasty code, riddled with conditionals that switch the app’s behavior depending on the class of transportation objects.

The Solution

The factory method pattern suggests that you replace direct object construction calls (using the operator) with calls to a special factory method. Don’t worry, the objects are still created via the operator, but it’s being called from within the factory . Objects returned by a factory method are often referred to as “”.

Logistics (Creator) Structure

At first glance, this change may look pointless: we just moved the constructor call from one part of the program to another. However, consider this, now you can override the factory method in a subclass and change the class of products being created by the method.

There’s a slight limitation though, . Also, the factory method in the base class should have its return type declared as this interface.

Transport (Product) Structure

For example, both and classes should implement the interface, which declares a method called . Each class implements this method differently: trucks deliver cargo by land, ships deliver cargo by sea. The factory method in the class returns objects, whereas the factory method in the class returns .

The code that uses the factory method (often called the client code) between the actual products returned by various subclasses. The client treats all the products as abstract . The client knows that all transport objects are supposed to have the method, but exactly how it works isn’t important to the client.

The Structure

In this structure diagram, we have a class that has the main function to create a product. and is the implementation of the class.

This class is needed to create some “”. So we create the interface. You must add your needs to your product class to this interface. For example, if you want to create a and product class that has the same method called , you must add method to this interface.

The and is the implementation of the interface.

So, in this structure, we can say that will produce a , will produce a , and so on.

As you can see, it’s easy to add a new product and creator with the factory method pattern, without changing your codebase.

FYI, some programmers like to change the name of the “Creator” class to the “Factory“ class. The responsibility is still the same, to create a product, but only the name is changed. For example, if we named a , we can also change this name to .

It’s Coding Time!

Let’s try to implement the factory method pattern using Kotlin language. We will make the in a factory method pattern based on the structure above.

First of all, we need to create an abstract Logistic (Creator) class.

In this Logistic class, we declare abstract function that return type. This function will be overridden by the subclass and used to create a product and then return in type.

And then, we declare the method to start to deliver our Transport product (for example, if we have created a product, we can start delivery when the client code calls this method).

We need to implement a and class that extends the Logistic abstract class.

In this class, we need to override the method to return the Ship object, because Ship will work only in the sea. Make sense right?

And in the class, we need to override the method to return the object.

After that, let’s create our Transport interface.

This interface will act as a type and the method declaration of our product. Let’s make our product class that implements this interface.

In class, we override the method to simulate deliver this object.

And in the class, we override the method to simulate deliver this object.

Our code’s ready. Let’s create a class to test our code.

We’ll try to create using using , and deliver it in 5 times. The following code will result in output:

Delivering Ship with id: Ship@2c7b84de
Delivering Ship with id: Ship@3fee733d
Delivering Ship with id: Ship@5acf9800
Delivering Ship with id: Ship@4617c264
Delivering Ship with id: Ship@36baf30c
Delivering Truck with id: Truck@7a81197d
Delivering Truck with id: Truck@5ca881b5
Delivering Truck with id: Truck@24d46ca6
Delivering Truck with id: Truck@4517d9a3
Delivering Truck with id: Truck@372f7a8d

Congrats!, you’ve already implemented the factory method pattern.

Now, maybe you wonder how to add a new type of logistic? let’s say we want to add an with the product .

We just need to add the creator,

and the Product,

That’s it! now you can use

val logistic = AirLogistic()

to start to deliver our Plane to the customer! :)

“Oh I see.., But that’s code only produce 1 product per creator. How to add a new type of product?, maybe with this AirLogistic, we need to send a to some island that doesn’t have an airport”

In this case, we need to implement a creator that can produce of products. I will explain to you how to do it in Part 2 of this post. This post will be too long if I explain it here XD.

Review Session

Photo by Charles 🇵🇭 on Unsplash

After all of that theory and code practice, we can conclude that implementing a factory method is simple as:

  1. .This interface should declare methods that make sense in every product.
  2. The return type of the method should match the common product interface.
  3. . One by one, replace them with calls to the factory method while extracting the product creation code into the factory method.
  4. . Override the factory method in the subclasses and extract the appropriate bits of construction code from the base method.
  5. .
  6. . If there’s something left, you can make it a default behavior of the method.

When to use Factory Method?

  • Use the Factory Method when you don’t know beforehand the exact types and dependencies of the objects your code should work with.
  • Use the Factory Method when you want to provide users of your library or framework with a way to extend its internal components.
  • Use the Factory Method when you want to save system resources by reusing existing objects instead of rebuilding them each time.

The Pros

  • You avoid tight coupling between the creator and the concrete products.
  • Single Responsibility Principle. You can move the product creation code into one place in the program, making the code easier to support.
  • Open/Closed Principle. You can introduce new types of products into the program without breaking existing client code.

The Cons

  • The code may become more complicated since you need to introduce a lot of new subclasses to implement the pattern. The best-case scenario is when you’re introducing the pattern into an existing hierarchy of creator classes.

Relation with other patterns

  • Many designs start by using (less complicated and more customizable via subclasses) and evolve toward , , or (more flexible, but more complicated).
  • classes are often based on a set of , but you can also use to compose the methods in these classes.
  • You can use along with to let collection subclasses return different types of iterators that are compatible with the collections.
  • isn’t based on inheritance, so it doesn’t have its drawbacks. On the other hand, Prototype requires a complicated initialization of the cloned object. is based on inheritance but doesn’t require an initialization step.
  • is a specialization of . At the same time, a Factory Method may serve as a step in a large Template Method.

The Startup

Medium's largest active publication, followed by +524K people. Follow to join our community.

Ezra Lazuardy

Written by

Kotlin + Android Enthusiast. Writer @thestartup. Find me at

The Startup

Medium's largest active publication, followed by +524K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade