The factory method pattern defines an interface for creating an object but lets subclasses decide which class to instantiate.
Just like with the simple factory design pattern, you can just think of it as a smart constructor.
public interface ServerFactory {
Server createServer();
}
public interface Server {
String getType();
}
Unlike with the simple factory, the concrete implementations is of both the factories and the classes to create.
public class DatabaseServer implements Server {
@Override
public String getType() {
return "DatabaseServer";
}
}
public class WebServer implements Server {
@Override
public String getType() {
return "WebServer";
}
}
public class DatabaseServerFactory implements ServerFactory {
@Override
public Server createServer() {
return new DatabaseServer();
}
}
public class WebServerFactory implements ServerFactory {
@Override
public Server createServer() {
return new WebServer();
}
}
ServerFactory factory = new WebServerFactory();
Server server = factory.createServer();
System.out.println(server.getType()); // WebServer