Explain Codes LogoExplain Codes Logo

Design Patterns: Factory vs Factory method vs Abstract Factory

design-patterns
factory-pattern
factory-method-pattern
abstract-factory-pattern
Alex KataevbyAlex Kataev·Sep 11, 2024
TLDR

Factory, Factory Method, and Abstract Factory are critical design patterns for object creation in Java. The Factory pattern creates objects through a single method, guiding the route to the correct class based on input parameters. The Factory Method pattern depends on inheritance, letting subclasses dictate the type of created object. The Abstract Factory pattern manages families of related objects, without detailing concrete classes.

Let's see them in action:

// Factory pattern public class CarFactory { // Feel the need for speed? Let's make a car! public static Car getCar(String type) { if (type.equals("SUV")) { return new SUV(); // Off-roading in luxury. } else if (type.equals("Sedan")) { return new Sedan(); // Ah, the classic choice. } throw new IllegalArgumentException("Unknown car type... Did you try to order a spaceship?"); } } // Factory Method pattern public abstract class CarCreator { // Factory Method: Allowing subclasses to throw a wrench into our plans. abstract Car createCar(); public Car orderCar(String type) { Car car = createCar(); // May include optional racing stripes. return car; } } // Abstract Factory pattern public interface CarFactory { Car createSedan(); // Luxury is just a method call away. Car createSUV(); // Channel your inner adventurer. } // Usage: CarFactory factory = new ConcreteCarFactory(); // As easy as shopping online.

Opt for the Factory pattern when clarity is desired, the Factory Method pattern when flexibility is crucial, and the Abstract Factory pattern for handling intricate object families.

How to choose the right pattern

When your application has a singular product that requires no complex decision logic for creation, the Factory pattern serves best. It's as simple as input and output—customers' orders in, products out.

The Factory Method pattern is your ally when you're dealing with multiple subclasses of a superclass. Here, your code maintains neatness while gaining the flexibility to introduce new object types without messing around with the client code.

When you're facing the hustle of creating inter-related sets of multiple families of objects, call upon the mighty Abstract Factory pattern. If your design smells like a mess of factories, maybe it's time to streamline with an abstract factory.

Real-world analogies

Imagine different dining experiences inside a shopping mall:

🍔 - Fast-Food Joint (Factory): You're hungry and looking for a quick bite. You see a fast-food joint up ahead and decide to grab a burger.

🍕🍝 - Italian Restaurant (Factory Method): You want to indulge a bit. The Italian restaurant in the corner offers various dishes like pizza or spaghetti, all on one menu.

🍣🍱🍙 - Sushi Market (Abstract Factory): Craving authentic Asian cuisine, you step into the sushi market. At different stands, you can get Sushi, Bento, or Onigiri, each crafted by specialists in their area.

Just like each food outlet serves a unique culinary experience, each design pattern offers distinct solutions to your software design needs.

Boosting your code with patterns

Scalability and reusability

In a scalable system, Factory Method lays excellent groundwork. This pattern allows the introduction of new object types without any changes to client code. Moreover, the Abstract Factory pattern follows the open-closed principle, enabling system growth without disrupting existing code.

Design patterns enhance reusability in your applications. Pattern like Factory and Factory Method encapsulate object creation, centralizing common instantiation logic and reducing code redundancy.

Dependency Injection

The Abstract Factory pattern offers a clean way of implementing Dependency Injection. Define interfaces for creating sets of related objects, freeing classes that rely on these products from knowing their concrete classes. This pattern eases system maintenance and evolution.

Creating Robust Software Structures

The object-creation process affects the overall structure of your application. The Factory patterns help you build robust and flexible structures:

  • Factories hide the new operator behind a single facade, encapsulating object instantiation.
  • Abstract Factories create families of products, enforcing their use together and enhancing consistency.
  • Factory Method pattern delegates object creation to subclasses, decoupling the client code from concrete classes, hence boosting flexibility.

Mastering pattern implementation

Mimic Real World: Code should imitate real-life scenarios. Factory Methods are like toolkits, Abstract Factories are entire factories containing a variety of toolkits.

Modular Design: Factories play a major role in enforcing modularity in your system. They centralize object creation, minimizing dependency and adhering to Single Responsibility Principle.

Naming Conventions: Name your factories descriptively, WindowFactory over Factory, to clear any ambiguity.

Respect the Gang of Four: Take guidance from the original Gang of Four patterns. However, remember: design patterns are flexible, not set in stone. Adapt them to suit your project needs.