Design Patterns - Factory

Also known as the simple factory pattern, the factory pattern is a creational pattern that creates objects without exposing how the object is created to the client by referring to the newly created object through a common interface. You can just think of it as a smart constructor.

As the name “Simple Factory” implies, this pattern is a simplified version of the Factory Method pattern.

The common interface

public interface Server {
	String getType();
}

Concrete implementations

public class DatabaseServer implements Server {

	@Override
	public String getType() {
		return "DatabaseServer";
	}

}

public class MailServer implements Server {

	@Override
	public String getType() {
		return "MailServer";
	}

}
public class WebServer implements Server {

	@Override
	public String getType() {
		return "WebServer";
	}

}

The factory

public class ServerFactory {

	public Server createServer(String type) {
		switch (type) {
			case "database":
				return new DatabaseServer();
			case "mail":
				return new MailServer();
			case "web":
				return new WebServer();
		}
		throw new IllegalArgumentException("There is no such server type");
	}

}

Usage from the client’s perspective

ServerFactory factory = new ServerFactory();
Server server = factory.createServer("web");
System.out.println(server.getType()); // WebServer