The Simple Factory pattern is a creational design pattern that provides a way to encapsulate object creation logic. Instead of directly instantiating classes with the new keyword, a dedicated factory class decides which concrete implementation to return based on provided input. This promotes loose coupling and centralizes change when new product types are added.
This example demonstrates the pattern using a mythological scenario: a creator (Nüwa) produces diffferent kinds of beings (Male, Female, Robot) depending on the input character ('M', 'W', or 'R'). The factory method receives the character and returns the corresponding object.
Class Diagram
The design consists of a Person interface (or abstract class) declaring a common method, concrete implementations (Male, Female, Robot) that impelment that interface, and a factory class (Creator) with a static method that inspects the parameter and instantiates the appropriate class. A client (e.g., a main program) collects input and calls the factory method.
Code Implementation
Person.java
public interface Person {
void showType();
}
Male.java
public class Male implements Person {
public Male() { }
@Override
public void showType() {
System.out.print("Created a male being");
}
}
Female.java
public class Female implements Person {
public Female() { }
@Override
public void showType() {
System.out.print("Created a female being");
}
}
Robot.java
public class Robot implements Person {
public Robot() { }
@Override
public void showType() {
System.out.print("Created a robot");
}
}
Creator.java (Factory Class)
public class Creator {
public static Person buildPerson(String input) {
if (input == null) {
return null;
}
char code = input.toUpperCase().charAt(0);
switch (code) {
case 'M':
return new Male();
case 'W':
return new Female();
case 'R':
return new Robot();
default:
return null;
}
}
}
Main.java (Client)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter parameter (M, W, or R): ");
String userInput = scanner.nextLine().trim();
scanner.close();
Person createdPerson = Creator.buildPerson(userInput);
if (createdPerson != null) {
createdPerson.showType();
} else {
System.out.println("Invalid input: no matching type.");
}
}
}
The factory method buildPerson uses a switch statement to map the input character to the correct concrete class. This centralizes creation logic, making it easy to add new being types (e.g., an 'A' for Alien) by modifying only the factory and adding a new class. The client remains unaware of which concrete class is instantiated.