Flutter Design Patterns: 10 — Factory Method
An overview of the Factory Method design pattern and its implementation in Dart and Flutter
Previously in the series, I have analysed a design pattern that is commonly used in our day-to-day programming, sometimes even without considering it — Iterator. In this article, I would like to analyse and implement one of the creational design patterns — Factory Method.
Update 2022–09–15: I moved this blog to my personal website. For a better reading experience, up to date articles, interactive code examples and some extra content FOR FREE, check kazlauskas.dev.
Table of Contents
- What is the Factory Method design pattern?
- Other articles in this series
- Your contribution
What is the Factory Method design pattern?
Factory Method, also known as Virtual Constructor, belongs to the category of creational design patterns. The intention of this design pattern is described in the GoF book:
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
That is, the Factory Method design pattern defines an interface for a class responsible for creating an object, hence deferring the instantiation to specific classes implementing this interface. This resolves the issue of creating objects directly within the class which uses them.
Also, it enables compile-time flexibility via subclassing. When objects are created within the class, it is very inflexible since you cannot change the instantiation of the object independently from the class — the class is committed to a particular object. By implementing the pattern, subclasses can be written to redefine the way an object is…