在Java第4版中思考 - 是否有必要建立一个工厂来隔离实现代码?

时间:2016-05-10 14:48:09

标签: java design-patterns

我正在阅读#34;思考Java第4版"。在章节"接口"和子章节"接口和工厂",它陈述以下

  

接口旨在成为多个实现的网关,   并且产生适合界面的对象的典型方法是   工厂方法设计模式。而不是调用构造函数   直接,你在工厂对象上调用一个创建方法   产生一个接口的实现 - 这种方式,理论上,你的   代码与接口的实现完全隔离,   从而可以透明地交换一个实现   另一个。这是一个展示工厂结构的演示   方法:

(为了便于参考,我的问题后引用的示例代码)

我的问题是,为什么我们不做这个" serviceConsumer"方法就像

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

在这种情况下,代码取决于界面"服务"但不是实施。 (它也可以"交换"透明,不是吗?)。所以,我并没有真正达到使用" factory"这里以及它在开始时所说的内容。

-----------------------------以下引用"用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 
*/ //:~

2 个答案:

答案 0 :(得分:2)

没有什么可以阻止你编写这样的方法,引用的语句是关于对象本身的创建。

  

在这种情况下,代码取决于接口“服务”而不是实现

在这两种情况下,代码都取决于界面,区别在于,在您的实现中,Service是在方法serviceConsumer之外创建的

答案 1 :(得分:0)

如果您真正使用Factory Method,也许会更清楚。 TIJ示例没有任何上下文。

我最喜欢的例子是Collection.iterator(),其中CollectionServiceFactoryIteratorService。您可以在serviceConsumer()中查看来电,但请注意以下事项:

Collection c = new ArrayList();  // ArrayList is a Factory for its iterator
Iterator i = c.iterator();  // getService()
if (i.hasNext()) { ...} 

如果serviceConsumer是打印集合的方法(而不是没有上下文的方法),您可以看到传递ServiceFactoryArrayList)比传递{{1}更好(Service)。使用它有更多的封装(服务的细节隐藏在方法中)。

以下是一些有助于理解相似之处的UML图表:

工厂方法模式

UML for factory method similar to GoF

TIJ示例

UML for the TIJ example

Collection.iterator()

UML for the factory method pattern used in Collection.iterator()

注意:粉色类实际上是匿名类,它们实现与Collection对应的Iterator接口类型。它们通常不是客户端将以任何其他方式(隐藏)实例化的类。