Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding the Simple Factory Pattern

Tech May 15 1

The Simple Factory Pattern is a creational design approach that provides a centralized mechanism for creating objects. Although it is not formally included in the Gang of Four's 23 design patterns, it is widely practiced and often referred to as the Static Factory Method pattern. Its primary objective is to decouple the client code from the complex logic of object instantiation.

This pattern is particularly beneficial when the construction of an object involves complex processes or when the system needs to manage multiple variations of a similar object. By delegating the creation responsibility to a factory class, the client does not need to know the specific details of how an object is created or initialized; they simply request an instance based on a parameter.

Core Components

The structure of the Simple Factory Pattern typically involves three key roles:

  • Factory Class: Contains the static logic required to create instances of various types. It decides which class to instantiate based on the provided input.
  • Product Interface: An abstract interface or class that defines the common contract for all objects created by the factory.
  • Concrete Products: Sepcific implementations of the product interface that the factory produces.

Implementation Example

Consider a scenario involving a payment processing system. The system needs to handle different payment methods like Credit Cards and PayPal. First, define a common interface for the payment processors:

public interface PaymentProcessor {
    void executePayment(double amount);
}

Next, implement the concrete payment processors:

public class CreditCardProcessor implements PaymentProcessor {
    @Override
    public void executePayment(double amount) {
        System.out.println("Processing credit card payment: $" + amount);
    }
}

public class PayPalProcessor implements PaymentProcessor {
    @Override
    public void executePayment(double amount) {
        System.out.println("Processing PayPal payment: $" + amount);
    }
}

Create the factory class responsible for selecting the appropriate processor:

public class PaymentFactory {
    public static PaymentProcessor createProcessor(String type) {
        if (type == null) {
            return null;
        }
        if (type.equalsIgnoreCase("CREDIT")) {
            return new CreditCardProcessor();
        } else if (type.equalsIgnoreCase("PAYPAL")) {
            return new PayPalProcessor();
        }
        throw new IllegalArgumentException("Unknown payment type: " + type);
    }
}

Finally, the client code interacts with the factory to retrieve the necessary object without knowing the specifics of its creation:

public class ClientApplication {
    public static void main(String[] args) {
        PaymentProcessor credit = PaymentFactory.createProcessor("CREDIT");
        credit.executePayment(150.00);

        PaymentProcessor paypal = PaymentFactory.createProcessor("PAYPAL");
        paypal.executePayment(75.50);
    }
}

Advantages and Disadvantages

Advantages:

  • Separation of Concerns: The creation logic is isolated within the factory, preventing the client from dealing with complex initialization code.
  • Loose Coupling: The client depends only on the interface and the factory, not on concrete classes.
  • Ease of Maintenance: Modifications to the creation process are centralized, reducing the risk of errors in multiple locations.

Disadvantages:

  • Violation of Open/Closed Principle: If a new product type is introduced, the factory class must be modified, which can complicate maintenance as the number of products grows.
  • Single Point of Failure: The factory class becomes a critical component; if it fails, the entire system may be affected.
  • Static Method Limitations: The use of static methods makes the factory difficult to subclass and mock during unit testing.

This pattern is best suited for scenarios where the number of product types is relatively small and fixed, and the creation logic is not overly complex.

Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.