top

Search

Software Key Tutorial

.

UpGrad

Software Key Tutorial

Factory Design Pattern in Java

Introduction

Welcome to this comprehensive tutorial where we delve into the nuances of the factory design pattern in Java. This tutorial is designed for seasoned professionals eager to expand their knowledge base and polish their Java programming skills. In this tutorial, we aim to provide a comprehensive understanding of the factory design pattern, its advantages, usage, and real-world applications.

Overview

The factory design pattern provides a method or a pattern for creating objects in a superclass but allows subclasses to alter the type of objects created. This tutorial will shed light on the practical advantages and implementation of the factory design pattern in Java.

The Advantages of Factory Design Pattern

The factory design pattern is a powerful tool in object-oriented programming that brings a host of benefits. Here is an expanded discussion of the primary advantages it offers:

  1. Abstraction of Object Creation:

One of the most significant benefits of the factory design pattern is the abstraction it provides in the object creation process. The factory design pattern allows objects to be created without exposing the intricacies of the instantiation logic to the client. This leads to a modular, cleaner, and more understandable code structure. Code readability is significantly enhanced, reducing complexity and increasing maintainability.

  1. Scalability:

The factory design pattern is known for facilitating scalability, another considerable advantage for developers. Developers can add new classes or modify existing ones with ease. They can create a new factory that inherits from an existing factory to override the object creation method and create a new object type. This fosters efficient code management and a scalable codebase, crucial for maintaining and expanding large software systems.

  1. Encourages Loose Coupling:

The factory design pattern promotes loose coupling, which leads to a flexible and adaptable system. It separates the object creation process from the actual usage of the objects, keeping the client code independent of the concrete classes used. This allows for changes in the class hierarchy or object creation logic without impacting the client code, increasing adaptability and robustness.

  1. Real-World Applications:

The factory design pattern is not just theoretical but has significant real-world applications. It finds extensive use in core Java libraries and frameworks like Spring Boot, which makes heavy use of this pattern for creating bean instances. Its relevance in such high-impact, real-world programming scenarios underlines the factory design pattern’s practical utility and importance.

Usage of Factory Design Pattern

The factory design pattern is a popular software design pattern employed in real-world scenarios where there's a need for creating objects without exposing the instantiation logic to the client and providing a common interface to all the newly created objects. Here are some specific uses and applications of the factory design pattern:

  1. User Interface (UI) Controls Creation:

In creating UI controls, the factory design pattern is vital. It helps manage the creation of diverse types of UI controls like buttons, checkboxes, dropdowns, etc. For instance, based on the running environment (like Windows, Mac, or Linux), the factory design pattern can create appropriate controls, ensuring an enhanced and seamless user experience.

  1. Hiring Agency Applications:

The factory design pattern is apt for handling the object creation process in a hiring agency application. Different roles like a developer, tester, manager, etc., can be represented as objects. The factory design pattern ensures the smooth creation and management of these role-based objects, facilitating a seamless hiring process.

  1. Document Management Systems:

Document management systems often use the factory design pattern to create different types of documents like PDF, Word, Excel, etc., based on user requirements. The pattern ensures the document's accurate creation, keeping the client oblivious to the instantiation logic.

  1. Frameworks and Libraries:

Numerous programming frameworks and libraries, like Spring Boot, heavily employ the factory design pattern. In the case of Spring Boot, it utilizes this pattern for creating bean instances. Depending on the bean definition in the Spring Configuration file, the appropriate bean is instantiated, which underscores the factory design pattern’s practicality and usefulness.

UML for Factory Method Pattern

Here's a representation of the factory method pattern using UML-like notation:

Here are the core components of this method:

Creator: Declares the factory method that returns a Product object. It may also include other methods that use the Product.

ConcreteCreator: Implements the factory method to create instances of ConcreteProduct. It overrides the factory method to produce specific product variations.

Product: Defines interfaces of objects created by the factory method.

ConcreteProduct: Represents the objects that the factory method creates and implements the Product interface.

Here is an example of using the factory method pattern where different types of shapes are created using this pattern:

Code:

public class Main {
    public static void main(String[] args) {
        // Create a Circle using CircleFactory
        ShapeFactory circleFactory = new CircleFactory();
        Shape circle = circleFactory.createShape();
        circle.draw(); // Output: Drawing a Circle
        
        // Create a Square using SquareFactory
        ShapeFactory squareFactory = new SquareFactory();
        Shape square = squareFactory.createShape();
        square.draw(); // Output: Drawing a Square
    }
}
// Product interface
interface Shape {
    void draw();
}

// Concrete Product: Circle
class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing a Circle");
    }
}

// Concrete Product: Square
class Square implements Shape {
    public void draw() {
        System.out.println("Drawing a Square");
    }
}

// Creator interface
interface ShapeFactory {
    Shape createShape();
}

// Concrete Creator: Circle Factory
class CircleFactory implements ShapeFactory {
    public Shape createShape() {
        return new Circle();
    }
}

// Concrete Creator: Square Factory
class SquareFactory implements ShapeFactory {
    public Shape createShape() {
        return new Square();
    }
}

In this example, the ShapeFactory is the Factory Method, and CircleFactory and SquareFactory are the Concrete Creators. Circle and Square are Concrete Products. The client code can then use the appropriate factory to create shapes without worrying about the specific implementation details.

In the main method, you first create instances of the Circle and Square factories. Then, you use these factories to create Shape objects (circle and square). When calling the draw method on these objects, you'll see the appropriate output based on whether you're drawing a circle or a square.

Factory Design Pattern Super Class

In the Factory Method design pattern, the superclass or interface that defines the Factory Method is often referred to as the "Creator" interface or class. This Creator class is responsible for declaring the factory method that subclasses will implement to create objects.

Here's an example of a Creator superclass in the context of the Factory Method pattern:

Code:

// Creator interface (Superclass)
interface DocumentCreator {
    Document createDocument();
}

// Concrete Creator: Create HTML documents
class HtmlDocumentCreator implements DocumentCreator {
    public Document createDocument() {
        return new HtmlDocument();
    }
}

// Concrete Creator: Create PDF documents
class PdfDocumentCreator implements DocumentCreator {
    public Document createDocument() {
        return new PdfDocument();
    }
}

// Product interface (Superclass)
interface Document {
    void open();
    void close();
}

// Concrete Product: HTML Document
class HtmlDocument implements Document {
    public void open() {
        System.out.println("Opening HTML document");
    }
    public void close() {
        System.out.println("Closing HTML document");
    }
}

// Concrete Product: PDF Document
class PdfDocument implements Document {
    public void open() {
        System.out.println("Opening PDF document");
    }
    public void close() {
        System.out.println("Closing PDF document");
    }
}

public class Main {
    public static void main(String[] args) {
        DocumentCreator creator1 = new HtmlDocumentCreator();
        Document htmlDocument = creator1.createDocument();
        htmlDocument.open();
        htmlDocument.close();
        
        DocumentCreator creator2 = new PdfDocumentCreator();
        Document pdfDocument = creator2.createDocument();
        pdfDocument.open();
        pdfDocument.close();
    }
}

In this example, the DocumentCreator interface acts as the Creator superclass. Concrete creators like HtmlDocumentCreator and PdfDocumentCreator implement the factory method createDocument() to create instances of Document objects (HtmlDocument and PdfDocument). The Document interface is the superclass for the products being created.

Using the factory method pattern, the client code (in the main method) can create different types of documents without needing to know their exact implementations. This promotes flexibility, separation of concerns, and extensibility in the codebase.

Factory Design Pattern Sub-classes

In the Factory Method design pattern, the subclasses that implement the factory method in the Creator class/interface are responsible for creating specific instances of products. These subclasses are often referred to as "Concrete Creators." Each Concrete Creator corresponds to a specific type of product that needs to be created.

In this example, HtmlDocumentCreator and PdfDocumentCreator are Concrete Creators. They implement the factory method createDocument(), which returns instances of Concrete Products (HtmlDocument and PdfDocument). These Concrete Creators determine the specific type of product to be created and return the appropriate instance.

By having different Concrete Creators, you can easily add new document types (products) by implementing new Concrete Creators without modifying the client code. This separation of responsibilities makes the code more modular and maintainable.

Factory Class

In the factory method pattern, the factory class (or factory) is responsible for creating instances of objects, and it encapsulates the creation process. This class often includes a factory method that subclasses implement to create different variations of products. The factory class abstracts the creation logic from the client code, promoting loose coupling and extensibility.

Here is an example of using the factory class:

// Product: Pet interface
interface Pet {
    void play();
}

// Concrete Products: Cat, Dog, and Bird
class Cat implements Pet {
    public void play() {
        System.out.println("Cat is playing.");
    }
}

class Dog implements Pet {
    public void play() {
        System.out.println("Dog is playing.");
    }
}

class Bird implements Pet {
    public void play() {
        System.out.println("Bird is playing.");
    }
}

// Factory Class (Creator)
class PetFactory {
    public Pet createPet(String petType) {
        if (petType.equalsIgnoreCase("cat")) {
            return new Cat();
        } else if (petType.equalsIgnoreCase("dog")) {
            return new Dog();
        } else if (petType.equalsIgnoreCase("bird")) {
            return new Bird();
        } else {
            throw new IllegalArgumentException("Invalid pet type.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        PetFactory petFactory = new PetFactory();
        
        Pet myCat = petFactory.createPet("cat");
        Pet myDog = petFactory.createPet("dog");
        Pet myBird = petFactory.createPet("bird");
        
        myCat.play();  // Output: Cat is playing.
        myDog.play();  // Output: Dog is playing.
        myBird.play(); // Output: Bird is playing.
    }
}

A Real-World Example of Factory Method

Here is a real-world example of the factory method pattern being applied to the GUI framework:

Here are the components of the method:

WidgetFactory: This is the Creator interface that declares the factory method createWidget() for creating Widget objects.

ButtonFactory and TextFieldFactory: These are Concrete Creators that implement the createWidget() method to create instances of Button and TextField respectively.

Checkbox, Button, and TextField: These are Concrete Products that implement the draw() method from the Widget interface. They represent different types of widgets that can be created.

Here is an example:

// Widget interface
interface Widget {
    void draw();
}

// Concrete Product: Button
class Button implements Widget {
    public void draw() {
        System.out.println("Drawing a button");
    }
}

// Concrete Product: Checkbox
class Checkbox implements Widget {
    public void draw() {
        System.out.println("Drawing a checkbox");
    }
}

// Concrete Product: TextField
class TextField implements Widget {
    public void draw() {
        System.out.println("Drawing a text field");
    }
}

// Creator interface
interface WidgetFactory {
    Widget createWidget();
}

// Concrete Creator: ButtonFactory
class ButtonFactory implements WidgetFactory {
    public Widget createWidget() {
        return new Button();
    }
}

// Concrete Creator: TextFieldFactory
class TextFieldFactory implements WidgetFactory {
    public Widget createWidget() {
        return new TextField();
    }
}
public class Main {
    public static void main(String[] args) {
        WidgetFactory buttonFactory = new ButtonFactory();
        Widget button = buttonFactory.createWidget();
        button.draw(); // Output: Drawing a button
        
        WidgetFactory textFieldFactory = new TextFieldFactory();
        Widget textField = textFieldFactory.createWidget();
        textField.draw(); // Output: Drawing a text field
    }
}

Conclusion

Wrapping up this tutorial, we hope to have provided a comprehensive understanding of the factory design pattern in Java. Mastering this pattern can significantly enhance your code's quality by improving its flexibility, modularity, and overall manageability. It's a powerful tool for Java programmers who are on a continuous journey of learning and upskilling.

FAQs

  1. What is an example of a factory design pattern in Java? 

In Java, the factory design pattern can be applied when creating objects that share a common interface but have different class implementations, based on the provided input parameters.

  1. Why use the factory design pattern? 

The factory design pattern offers a simple yet efficient method for object creation. By hiding the instantiation logic from the client, it promotes code reusability and modularity.

  1. Is factory design pattern a creational pattern? 

Yes, the factory design pattern is indeed a creational pattern as it deals with object creation mechanisms, striving to create objects in a manner suitable to the situation.

  1. What is the difference between factory and abstract factory design pattern? 

The factory design pattern creates an instance of several derived classes based on interfaced data or events. In contrast, the abstract factory design pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

  1. How is the factory design pattern used in Spring Boot?

Factory design pattern in Spring Boot is extensively used to manage and create bean instances. When a bean is requested, Spring Boot utilizes a factory to create the bean instance, encapsulating the object creation logic and promoting loose coupling. This allows for efficient bean management and easy code scalability.

Leave a Reply

Your email address will not be published. Required fields are marked *