Simple Factory

Simple Factory

Simple Factory is the way of creating objects to encapsulate the logic of entity. Client doesn't know the actual logic of entity.

Simple Factory is the way of creating objects for client without exposing the object creation logic to the client.

Real world example

Let's consider, you want a Mac laptop. You simply can get one from a factory so you don't need to learn anything about making the laptop.

Example

Laptop interface and the implementation

interface Laptop {
  public int getScreenSize();
}
 
class MacLaptop implements Laptop {
  protected int screenSize;
 
  public MacLaptop(int screenSize) {
    this.screenSize = screenSize;
  }
 
  public int getScreenSize() {
    return this.screenSize;
  }
}

Laptop factory that make the laptop

class LaptopFactory {
  public static Laptop makeLaptop(int screenSize) {
    return new MacLaptop(screenSize);
  }
}

It can be used

// Make me a 14 inch laptop
Laptop macLaptop = LaptopFactory.makeLaptop(14);
System.out.println(macLaptop.getScreenSize());

Source Code in Java (opens in a new tab)