Design patterns Factory Simple factory (Java)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A factory decreases coupling between code that needs to create objects from object creation code. Object creation is not made explicitly by calling a class constructor but by calling some function that creates the object on behalf the caller. A simple Java example is the following one:

interface Car {
}

public class CarFactory{
  static public Car create(String s) {
    switch (s) {
    default:
    case "us":
    case "american": return new Chrysler();
    case "de":
    case "german": return new Mercedes();
    case "jp":
    case "japanese": return new Mazda();
    }
  }
}

class Chrysler implements Car {
  public String toString() { return "Chrysler"; }
}

class Mazda implements Car {
  public String toString() { return "Mazda"; }
}

class Mercedes implements Car {
  public String toString() { return "Mercedes"; }
}

public class CarEx {
  public static void main(String args[]) {
    Car car = CarFactory.create("us");
    System.out.println(car);
  }
}

In this example, user just gives some hint about what he needs and the factory is free to construct something appropriate. It is a dependency inversion: the implementor of Car concept is free to return an appropriate concrete Car requested by the user which in turn doesn't know the details of the concrete object built.

This is a simple example of how factory works, of course in this example it is always possible to instantiate concrete classes; but one can prevent it by hiding concrete classes in a package, such that user is forced to use the factory.

.Net Fiddle for above example.



Got any Design patterns Question?