Flutter Design Patterns: 2 — Factory Method

Omer Shafique
2 min readOct 31, 2022

--

In this article, we will explore the Factory Method In Flutter. We will see how to implement a demo program and we are going to learn about how we can to use it in your flutter applications.

What Is a Factory Method?

How To Implement a Factory Method In Dart:

Conclusion

What Is a Factory Method?

The factory method is a creational design pattern, i.e., related to object creation. In the Factory pattern, we create objects without exposing the creation logic to the client and the client uses the same common interface to create a new type of object.

Factory Method Pattern says that just defines an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class & alter the type of objects that will be created.

The Factory Method Pattern is also known as Virtual Constructor.

How To Implement a Factory Method In Dart:

Create an abstract class Shape.

abstract class Shape {  void draw();
}

Now we’ll create an enum ShapeType of our types & factory constructor inside our Shape class that will take type as a parameter and based on that type that shape will be drawn. The class Shape is marked abstract to restrict direct initialization of Shape since the class has no execution for the draw().

enum ShapeType {
circle,
square
}
abstract class Shape {
factory Shape(ShapeType type) {
switch (type) {
case ShapeType.circle: return Circle();
case ShapeType.square: return Square();
default: return null;
}
}
void draw();
}

Now we’ll create two classes Circle & Square which implements Shape

class Circle implements Shape {
@override
void draw() {
print("Circle");
}
}
class Square implements Shape {
@override
void draw() {
print("Square");
}
}

Now we can create objects of Shape class with different types.

final shape1 = Shape(ShapeType.circle);
final shape2 = Shape(ShapeType.square);
shape1.draw();
shape2.draw();

Both shape1 and shape2 are of type Shape, however, one is a circle and the other is a square.

Conclusion:

In the article, I have explained the basic structure of Factory Design Patterns For Dart and Flutter; you can modify this code according to your choice.

I hope this blog will provide you with sufficient information on Trying up the Factory Design Patterns For Dart and Flutter in your projects. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

--

--