mardi 10 mai 2016

Thinking in Java 4th Edition - is it necessary to make a factory for isolating the code from implementation?

I am currently reading "Thinking in Java 4th edition". In the Chapter "Interface" and the sub-chapter "Interfaces and factories", it states the following

An interface is intended to be a gateway to multiple implementations, and a typical way to produce objects that fit the interface is the Factory Method design pattern. Instead of calling a constructor directly, you call a creation method on a factory object which produces an implementation of the interface—this way, in theory, your code is completely isolated from the implementation of the interface, thus making it possible to transparently swap one implementation for another. Here’s a demonstration showing the structure of the Factory Method:

(for easy reference, the example codes quoted after my question)

My question is that why don't we just make the "serviceConsumer" method to be like

public static void serviceConsumer(Service s) { 
    s.method1(); 
    s.method2(); 
} 

In this case, the code depends on the interface "Service" but not the implementation. (It can also "swap" transparently, isn't it?). So, I don't really get to the point of using "factory" here and what it states at start.

-----------------------------below quoted from "Thinking in Java"------------------------------

//: interfaces/Factories.java 
import static net.mindview.util.Print.*; 
interface Service { 
void method1(); 
void method2(); 
} 
interface ServiceFactory { 
Service getService(); 
} 
class Implementation1 implements Service { 
Implementation1() {} // Package access 
public void method1() {print("Implementation1 method1");} 
public void method2() {print("Implementation1 method2");} 
} 
class Implementation1Factory implements ServiceFactory { 
public Service getService() { 
return new Implementation1(); 
} 
} 
class Implementation2 implements Service { 
Implementation2() {} // Package access 
public void method1() {print("Implementation2 method1");} 
public void method2() {print("Implementation2 method2");} 
} 
class Implementation2Factory implements ServiceFactory { 
public Service getService() { 
return new Implementation2(); 
} 
} 
public class Factories { 
public static void serviceConsumer(ServiceFactory fact) { 
Service s = fact.getService(); 
s.method1(); 
s.method2(); 
} 
public static void main(String[] args) { 
serviceConsumer(new Implementation1Factory()); 
// Implementations are completely interchangeable: 
serviceConsumer(new Implementation2Factory()); 
} 
} /* Output: 
Implementation1 method1 
Implementation1 method2 
Implementation2 method1 
Implementation2 method2 
*///:~ 

Aucun commentaire:

Enregistrer un commentaire