Factory Design Pattern

Factory Design Pattern

The Factory Pattern is a powerful design pattern that simplifies object creation, enhances code organization, and promotes maintainability. By abstracting the creation process and delegating it to subclasses or specialized factories, it enables flexible, extensible, and clean code.

Key Components of Factory Design Pattern

  1. Product Interface/Abstract Class: This defines the interface or abstract class that represents the products to be created by the factory. It declares the common methods that the concrete products must implement.

  2. Concrete Products: These are the specific classes that implement the product interface or extend the abstract class. Each concrete product represents a different variation or implementation of the product interface.

  3. Factory Class: The factory class is responsible for creating and returning instances of the concrete products. It provides a method or methods to create objects based on certain conditions or parameters.

Implementation

OS Interface:

package FactotyDesign;

public interface OS {
    public void Name();
}

OS Class:

package FactotyDesign;

public class Linux implements OS{

    @Override
    public void Name() {
        System.out.println("OS Name : Linux");
    }
}
package FactotyDesign;

public class Android implements OS{
    @Override
    public void Name() {
        System.out.println("OS Name : Android");
    }
}
package FactotyDesign;

public class Windows implements OS{

    @Override
    public void Name() {
        System.out.println("OS Name : Windows");
    }
}

Factory Class:

package FactotyDesign;

public class OSFactory {
    OS getOS(String device){
        if(device.equals("Mobile")) return new Android();
        else if(device.equals("DumbPC")) return new Windows();
        else return new Linux();
    }
}

Client Class:

package FactotyDesign;

public class main {
    public static void main(String[] args) {
//        Normal Object Creation
//        OS myOS = new Android();
//        myOS.Name();
//        Factory Design
        OS mobileOS = new OSFactory().getOS("Mobile");
        mobileOS.Name();
    }
}

Why we need Factory Design Pattern:

  1. The Factory Pattern encapsulates object creation logic, ensuring it remains hidden from client code.

  2. It allows for the addition of new object types (Concrete Products) without altering existing code.

  3. By centralizing object creation in factories, you can reuse the same factory logic across multiple parts of your application, reducing redundancy.

  4. The Factory Pattern enforces uniform object creation following a common interface (Product).

  5. The Factory Pattern plays a significant role in dependency injection frameworks, allowing for the creation and management of dependencies.