Software Design
Design Patterns
Programming
Factory Pattern
Object-Oriented Programming

Design Patterns Factory vs Factory method vs Abstract Factory

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Design patterns are essential solutions to common problems in software design, providing standardized methodologies to make code more efficient and easier to understand. Among these patterns, the Factory Pattern, Factory Method, and Abstract Factory pattern play critical roles in object creation. They help in encapsulating the instantiation of objects, which can make a system more modular, easier to test, and more accessible to modifications or extensions.

Factory Pattern

The Factory pattern is a creational pattern used in programming to help encapsulate object creation. The essence of this pattern is to create an interface for creating objects but allow subclasses to alter the type of objects that will be created. This is achieved by defining a separate method inside the factory class, whose job is to create objects.

For example, consider a UI library where we need to create various types of UI elements:

java
1public class ButtonFactory {
2    public static Button createButton(String type) {
3        if (type.equals("Windows")) {
4            return new WindowsButton();
5        } else if (type.equals("Linux")) {
6            return new LinuxButton();
7        } else {
8            throw new IllegalArgumentException("Unknown button type.");
9        }
10    }
11}

In the above example, ButtonFactory is responsible for creating buttons of various types. Using the factory pattern allows the client code to remain unaffected by the specifics of object creation.

Factory Method Pattern

An expansion of the Factory pattern, the Factory Method Pattern defines an interface for creating an object but lets subclasses decide which class to instantiate. This pattern lets a class defer instantiation to subclasses. In other words, instead of having a factory class creating the instances, each class has a method that creates and returns an instance of itself.

For instance, in a logging framework:

java
1abstract class Logger {
2    public abstract Log createLog();
3
4    public void logMessage(String message) {
5        Log log = createLog();
6        log.logMessage(message);
7    }
8}
9
10class FileLogger extends Logger {
11    @Override
12    public Log createLog() {
13        return new FileLog();
14    }
15}

Here, FileLogger overrides the createLog() method to return an instance of FileLog. Other subclasses could instantiate different types of logs.

Abstract Factory Pattern

The Abstract Factory Pattern provides a way to encapsulate a group of individual factories with a common goal. It is useful when there are interdependent products that need to be created together, and you want to ensure that your system remains independent from how these products are created and composed.

Consider an ecosystem for widgets that work across multiple operating systems. Each component (e.g., Buttons, Textboxes) could have different implementations in different operating systems (Windows, Linux):

java
1interface GUIFactory {
2    Button createButton();
3    TextBox createTextBox();
4}
5
6class LinuxFactory implements GUIFactory {
7    public Button createButton() {
8        return new LinuxButton();
9    }
10    public TextBox createTextBox() {
11        return new LinuxTextBox();
12    }
13}
14
15class WindowsFactory implements GUIFactory {
16    public Button createButton() {
17        return new WindowsButton();
18    }
19    public TextBox createTextBox() {
20        return new WindowsTextBox();
21    }
22}

By defining an interface GUIFactory, which concrete factories LinuxFactory and WindowsFactory implement, the system can instantiate objects based on the underlying operating system without having to bind to the specific classes of the platform.

Comparison Table

PatternDefinitionScope of Use
FactorySimple method for object creation.Useful when creating a single object.
Factory MethodDelegates instantiation to subclasses.Useful when there are multiple, similar methods or classes.
Abstract FactoryA hierarchy of factory classes with related products.Useful for complex constructions dependent on environment.

Conclusion

Understanding the differences between these patterns can greatly enhance your control over object creation in complex systems. While the factory patterns are often confused due to their similarities, recognizing the specific situations where each is applicable can lead to cleaner, more efficient code implementations and architecture.


Course illustration
Course illustration

All Rights Reserved.