?????Factory Design Pattern?????

Factory Design Pattern

Purpose: The Factory Pattern is used to create objects without specifying the exact class of object that will be created. It provides a way to delegate the instantiation logic to subclasses, making it easier to manage and scale object creation.

UML Diagram for Factory Design Pattern.

Components:

  1. Product Interface: Defines the interface for objects created by the factory.
  2. ConcreteProduct: Implements the Product interface and defines specific product variants.
  3. Creator (Factory): Declares a factory method that returns an object of type Product. It may also provide a default implementation.
  4. ConcreteCreator: Implements the factory method to create specific ConcreteProduct instances.

// Product interface
public interface Product {
    void use();
}

// ConcreteProductA class
public class ConcreteProductA implements Product {
    @Override
    public void use() {
        System.out.println("Using ConcreteProductA");
    }
}

// ConcreteProductB class
public class ConcreteProductB implements Product {
    @Override
    public void use() {
        System.out.println("Using ConcreteProductB");
    }
}

// Creator (Factory) interface
public abstract class Creator {
    public abstract Product factoryMethod();
}

// ConcreteCreatorA class
public class ConcreteCreatorA extends Creator {
    @Override
    public Product factoryMethod() {
        return new ConcreteProductA();
    }
}

// ConcreteCreatorB class
public class ConcreteCreatorB extends Creator {
    @Override
    public Product factoryMethod() {
        return new ConcreteProductB();
    }
}

// Main class to test the Factory Pattern
public class FactoryPatternDemo {
    public static void main(String[] args) {
        Creator creatorA = new ConcreteCreatorA();
        Product productA = creatorA.factoryMethod();
        productA.use();
        
        Creator creatorB = new ConcreteCreatorB();
        Product productB = creatorB.factoryMethod();
        productB.use();
    }
}

        

When to Use the Factory Design Pattern

The Factory Design Pattern is particularly useful in several scenarios:

  1. Object Creation Complexity: When the process of creating an object is complex or involves multiple steps, a factory method can encapsulate this complexity, providing a simple interface for object creation.
  2. Decoupling: When you want to decouple the client code from the specific classes it needs to instantiate. This allows you to change or extend the classes being instantiated without modifying the client code.
  3. Object Type Variability: When you need to create instances of different classes that implement a common interface or inherit from a common superclass. The factory pattern helps manage these different classes through a unified interface.
  4. Code Reusability: When you need to create a family of related objects but want to ensure that client code uses them consistently.
  5. Managing Object Lifecycle: When you need to manage the lifecycle of created objects or control their creation in a centralized place.

Consequences of Not Using the Factory Design Pattern

If you do not use the Factory Design Pattern, you might encounter several issues:

  1. Tight Coupling: The client code will need to know about the concrete classes it instantiates, leading to tight coupling between the client and the product classes. This makes the code harder to maintain and extend.
  2. Code Duplication: Without a factory, similar object creation code might be duplicated in multiple places, increasing maintenance effort and risk of errors.
  3. Reduced Flexibility: Changes to the object creation process require modifications in multiple places, making the code less flexible and harder to manage.
  4. Inconsistent Object Creation: Managing object creation in multiple places can lead to inconsistencies and bugs.

Example in Java

Scenario: Creating Different Types of Documents

Suppose you need to create different types of documents in a system, such as PDF and Word documents. Without using the Factory Design Pattern, you might end up with tightly coupled code:

Without Factory Pattern:


// Document interface
public interface Document {
    void open();
}

// PDFDocument class
public class PDFDocument implements Document {
    @Override
    public void open() {
        System.out.println("Opening PDF Document");
    }
}

// WordDocument class
public class WordDocument implements Document {
    @Override
    public void open() {
        System.out.println("Opening Word Document");
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        Document doc1 = new PDFDocument();
        doc1.open();

        Document doc2 = new WordDocument();
        doc2.open();
    }
}

        

Issues:

  • Tight Coupling: The Main class directly instantiates PDFDocument and WordDocument. Changing the implementation or adding new document types requires modifying the Main class.
  • Code Duplication: If the creation of documents is required in multiple places, you'll end up duplicating the instantiation code.

With Factory Pattern:


// Document interface
public interface Document {
    void open();
}

// Concrete Documents
public class PDFDocument implements Document {
    @Override
    public void open() {
        System.out.println("Opening PDF Document");
    }
}

public class WordDocument implements Document {
    @Override
    public void open() {
        System.out.println("Opening Word Document");
    }
}

// Factory class
public class DocumentFactory {
    public static Document createDocument(String type) {
        switch (type) {
            case "PDF":
                return new PDFDocument();
            case "Word":
                return new WordDocument();
            default:
                throw new IllegalArgumentException("Unknown document type");
        }
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        Document pdfDoc = DocumentFactory.createDocument("PDF");
        pdfDoc.open();

        Document wordDoc = DocumentFactory.createDocument("Word");
        wordDoc.open();
    }
}

        

Benefits:

  • Decoupling: The Main class does not need to know about the specific implementations of Document. It relies on the DocumentFactory to provide the appropriate instance.
  • Flexibility: Adding new document types only requires updating the DocumentFactory, without modifying the Main class.
  • Centralized Object Creation: All document creation logic is centralized in the factory, reducing code duplication and improving maintainability.

Summary

Use the Factory Design Pattern when you want to decouple object creation from the client code, manage complex creation logic, or ensure consistency in how objects are created. Not using the pattern can lead to tightly coupled code, duplication, and reduced flexibility, making it harder to manage and extend the system.

要查看或添加评论,请登录

Ankesh Mishra的更多文章

  • Securing Your App: Lessons from the Club

    Securing Your App: Lessons from the Club

    Imagine you're organizing an exclusive party at a high-end club. You want to ensure that only trusted and invited…

  • ?Decorator Pattern?

    ?Decorator Pattern?

    Decorator Pattern Summary Intent: The Decorator Pattern attaches additional responsibilities to an object dynamically…

  • ??Strategy Design Pattern??

    ??Strategy Design Pattern??

    ?? Understanding the Strategy Design Pattern through Uber Fare Calculation ?? In software design, flexibility and…

  • Singleton Design Pattern.

    Singleton Design Pattern.

    Approaches for Writing a Singleton Class While the Singleton design pattern might appear simple at first glance, its…

  • ?? Unlocking the Power of Criteria Query Language in Hibernate ??

    ?? Unlocking the Power of Criteria Query Language in Hibernate ??

    Are you looking for a flexible and type-safe way to build dynamic queries in Hibernate? Let’s dive into Criteria Query…

  • TABLE Generation Strategy

    TABLE Generation Strategy

    In Hibernate, an ORM (Object-Relational Mapping) framework for Java, the generation strategy is a way to generate…

  • Hibernate Entity Lifecycle

    Hibernate Entity Lifecycle

    ?? Understanding the Hibernate Lifecycle: From Transient to Detached Hibernate, a powerful ORM framework for Java…

    2 条评论

社区洞察

其他会员也浏览了