大家好!最近在看一些关于工厂设计模式的文章。如果把下面的代码的注释部分的代码都去掉,程序照样能按照设计要求执行出正确结果。但是去掉了间接获得对象的代码。我有点不明白,为何要浪费那么多功夫为每个实现类都创建间接访问方式而不直接创建对象。(本人分不多 仅送上20分)代码如下:
package interfaces;interface Service
{
void method1();
void method2();
}interface ServiceFactory//去掉
{
Service getService();
}class Implementation1Factory implements ServiceFactory//去掉
{
public Service getService()
{
return new Implementation1();
}
}class Implementation2Factory implements ServiceFactory//去掉
{
public Service getService()
{
return new Implementation2();
}
}class Implementation1 implements Service
{ @Override
public void method1() {
// TODO Auto-generated method stub
System.out.println("Impl1->method1()");
} @Override
public void method2() {
// TODO Auto-generated method stub
System.out.println("Impl1->method2()");
}

}class Implementation2 implements Service
{
@Override
public void method1() {
// TODO Auto-generated method stub
System.out.println("Impl2->method1()");
} @Override
public void method2() {
// TODO Auto-generated method stub
System.out.println("Impl2->method2()");
}
}public class Factories { public static void serviceConsumer(ServiceFactory sf) //Service
{
Service s = sf.getService();//去掉
s.method1();
s.method2();
}

public static void main(String[] args) {
Factories.serviceConsumer(new Implementation1Factory());
Factories.serviceConsumer(new Implementation2Factory());
//Factories.serviceConsumer(new Implementation1());
//Factories.serviceConsumer(new Implementation2());
}}

解决方案 »

  1.   

    如果创建一个对象需要做很多准备工作,这个时候就需要getService()准备了哟。
    如果现在又增加一种新的对象,你怎么办?如果增加很多新的对象怎么办?如果你已经在程序中用了很多次已经存在的对象,现在需要改变了 需要修改这个对象的初始化条件,你怎么办?
      

  2.   

    能不能简单介绍下实现与接口分离 光看概念不太懂 
    3楼的朋友: 如果创建很多对象 只要把新对象作为参数传递给Service 不是也一样 无论两个Implentation类里的初始化如何改变 貌似new Impletation1/2()传递参数的时候 都不会影响程序执行结果