Welcome to our comprehensive guide on the Java Factory Pattern! This tutorial is designed for both beginners and intermediates, so let's dive right in.
The Factory Pattern is a creational design pattern that provides an interface for creating objects in a super class, but allows subclasses to alter the type of objects that will be produced. In other words, it's a way to hide the complexity of object creation and provide a simple interface for creating objects.
Let's create a simple Factory class:
// Our Factory Interface
public interface Product {
void use();
}
// Concrete Product A
public class ConcreteProductA implements Product {
@Override
public void use() {
System.out.println("Using ConcreteProductA");
}
}
// Concrete Product B
public class ConcreteProductB implements Product {
@Override
public void use() {
System.out.println("Using ConcreteProductB");
}
}
// Our Factory Class
public class Factory {
// Simple Factory: creates objects directly
public static Product createProduct(String productType) {
if (productType.equalsIgnoreCase("A")) {
return new ConcreteProductA();
} else if (productType.equalsIgnoreCase("B")) {
return new ConcreteProductB();
}
throw new IllegalArgumentException("Invalid product type");
}
}In this example, we have a Product interface and two concrete implementations (ConcreteProductA and ConcreteProductB). The Factory class is responsible for creating Product objects.
To make our Factory more flexible, we can introduce an Abstract Factory:
// Our Abstract Factory
public abstract class AbstractFactory {
public abstract Product createProduct();
}
// Concrete Factory A
public class ConcreteFactoryA extends AbstractFactory {
@Override
public Product createProduct() {
return new ConcreteProductA();
}
}
// Concrete Factory B
public class ConcreteFactoryB extends AbstractFactory {
@Override
public Product createProduct() {
return new ConcreteProductB();
}
}In this example, we've added an AbstractFactory class that provides a common interface for creating Product objects. Each concrete factory (ConcreteFactoryA and ConcreteFactoryB) implements this interface and provides its own implementation of the createProduct() method.
public class Main {
public static void main(String[] args) {
// Using Simple Factory
Product product = Factory.createProduct("A");
product.use();
// Using Advanced Factory
AbstractFactory factoryA = new ConcreteFactoryA();
Product productFromFactoryA = factoryA.createProduct();
productFromFactoryA.use();
AbstractFactory factoryB = new ConcreteFactoryB();
Product productFromFactoryB = factoryB.createProduct();
productFromFactoryB.use();
}
}In this example, we're using both the Simple Factory and the Advanced Factory.
What does the Factory Pattern help in achieving?
What is the purpose of the Abstract Factory in the Advanced Factory Pattern?