Factory Method in Flutter

Syed Abdul Basit
5 min readSep 7, 2024

The Factory Method, one of the well-known “Gang of Four” design patterns.

🚫 The Limitation of Using Constructors for Object Creation

When we learn programming, we usually create objects using constructors. But is this always the best idea? 🤔

Not really. The big issue? You must know the exact class type to instantiate. 🏗️

⚠️ Why Is This a Problem?

While constructors seem convenient, what if your app needs to handle objects you haven’t thought of yet? 🤯

🎮 Example: Tower Defense Game

Let’s say you’re building a tower defense game 🏰, where users choose different towers. You might not know which towers they’ll prefer — or which new ones you’ll add in the future. 💡

🔧 Traditional Approach

  • You create a Splash Tower 💦 using one constructor.
  • A Long-Range Tower 🎯 has another constructor.
  • Same for a Slow Tower 🐢.

Seems fine, right? ✅ But when you want to add more towers later, it becomes problematic. 🆕

❓ The Problem

--

--

Responses (1)