Factory Constructor in Dart — Part 1

Saravanan M
Nerd For Tech
Published in
2 min readJun 25, 2021

Factory constructor is one of the confusing topics for beginners in dart. To understand it better, one must understand the factory design pattern first.

Image src : https://www.freepik.com/jcomp

What is Factory Design Pattern?

Definition: In a Factory pattern, we create objects without exposing the creation logic to the client and refer to newly created objects using a common interface.

If you’re confused, let me try to explain it via code and the factory construct.

If we need to create the object of these subclasses with the following criteria,

  1. Give Doberman instance, if the user wants a dog to guard
  2. Give Labrador instance, otherwise.

How can we naively do that?

This is fine in one place, what if you want this logic in multiple places? You have to repeatedly use the if-else statement. How can we simplify this? The answer is factory constructor.

Now we have moved the instance creation logic to the parent class. How can we use the construct?

To create a guard dog, use

Dog myGaurdDog = Dog.createDog(name:’Rocky’,gaurdDog:true);

Otherwise use,

Dog myPetDog = Dog.createDog(name:’Tommy’,gaurdDog:false);

Now if you look at the factory design pattern definition, it is more understandable

  1. we create objects without exposing the creation logic to the client

yes, we haven’t exposed the object creation logic to the client(main() method), it’s hidden inside our parent class ‘Dog’, the client needs to call the factory constructor with the required parameters to get the needed object.

2. We refer to newly created objects using a common interface.

This is also true, we are returning an instance of Labrador(or Doberman) with type Dog, not as Labrador(or Doberman). The parent class is the common interface here as it is compatible with both the sub-classes.

I hope, now you understood how the factory constructor makes our life much easier. Implementing a factory design pattern is not the only useful thing of the factory constructor. We can also implement caching features using the factory constructor. I will discuss ‘caching using factory’ in the next article and the ‘difference between named and factory constructors’ in the subsequent articles. Thank you.

--

--

Saravanan M
Nerd For Tech

Writes about Functional Programming, Web Development...