Skip to content

Instantly share code, notes, and snippets.

@philipschwarz
Created September 25, 2011 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipschwarz/1241180 to your computer and use it in GitHub Desktop.
Save philipschwarz/1241180 to your computer and use it in GitHub Desktop.
Separating use from construction - After
public class BusinessObject {
public void actionMethod() {
// Other things
//No Change!
Servicec myServiceObject = Service.getInstance();
myServiceObject.doService();
// Other things
}
}
abstract class Service {
private Service(){ //any needed construction behavior }
public static Service getInstance() {
return ServiceFactory.getService()
}
abstract void doService();
}
class ServiceFactory{
public static Service getService(){
if (someCondition) {
return new Service_Impl1();
} else {
return new Service_Impl2()
}
}
}
Service_Impl1 : Service {
void doService() { // one implementation }
}
Service_Impl2 : Service
void doService() { // different implementation
}
@jbrains
Copy link

jbrains commented Oct 3, 2011

I don't see how ServiceFactory helps here. It seems to muddy the waters. I would inline ServiceFactory.getService() and put the conditional logic directly into Service.getInstance() with a REFACTOR comment that says "push this decision out to clients!"

Making Service abstract certainly sounds reasonable, but a REFACTOR comment that says "make me an interface, please".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment