How to write Java?
No.1 static factory method replace constructor
- originally
interface Service{}
ServiceImp implements Service{}
Service service = new ServiceImp();
- singleton
public class Server{
private Service service = null;
public static Service getService(){
if(service == null){
service = new Service();
}
}
}
Service service = Server.getService();
- static factory method
// service provider framework
interface Provider{
Service getInstance();
}
public class Server{
private static HashMap<String, Provider> map = new HashMap<String, Provider>();
private static final DEFAULT_NAME = "Service";
public void registerDefault(Provdier p){
map.put(DEFAULT_NAME, p);
}
public void register(String name, Provdier p){
map.put(name, p);
}
public static Service getService(){
return getService(DEFAULT_NAME);
}
public static Service getService(name){
Provider p = map.get(name);
if(p == null){
throw new Exception(name);
}
return p.getInstance();
}
}
Server.registerDefault();
Service service = Server.getService();