Factory Method Pattern

Category : Java | Sub Category : Design Patterns | By Prasad Bonam Last updated: 2023-07-09 00:18:53 Viewed : 338


Factory Method Pattern:

The Factory pattern in Java is a creational design pattern that provides an interface for creating objects without specifying the exact class of the object being instantiated. It allows clients to create objects by delegating the responsibility of object instantiation to a factory class.

Here is an example of implementing the Factory pattern in Java:

  1. Define a common interface or abstract class for the objects you want to create. Lets call it Product:
java
public interface Product {
void doSomething();
}
  1. Create concrete classes that implement the Product interface:
java
public class ConcreteProductA implements Product {
public void doSomething() {
System.out.println("Doing something in ConcreteProductA");
}
}
public class ConcreteProductB implements Product {
public void doSomething() {
System.out.println("Doing something in ConcreteProductB");
} }
  1. Implement a factory class, which is responsible for creating the objects based on some criteria. Lets call it ProductFactory:
java
public class ProductFactory {
public Product createProduct(String type) {
if (type.equals("A")) {
return new ConcreteProductA();
} else if (type.equals("B")) {
return new ConcreteProductB();
}
return null;
} }
  1. Usage of the Factory pattern:
java
public class Main {
public static void main(String[] args) {
ProductFactory factory = new ProductFactory();
// Create an instance of ConcreteProductA using the factory

Product productA = factory.createProduct("A");
productA.doSomething();
// Output: Doing something in ConcreteProductA
// Create an instance of ConcreteProductB using the factory
Product productB = factory.createProduct("B");
productB.doSomething();
// Output: Doing something in ConcreteProductB
} }

In this example, the ProductFactory class encapsulates the object creation logic. It provides a method createProduct() that takes a parameter (type) to determine which type of product to create. The client code uses the factory to create objects without knowing the exact class being instantiated.

The Factory pattern promotes loose coupling and separates the responsibility of object creation from the client code. It allows for flexibility in adding new product types without modifying the client code.

Search
Related Articles

Leave a Comment: