日期:2014-05-20  浏览次数:20666 次

帮小弟看下这个匿名内部类的程序 有些地方不懂 在线等答案
interface Service{
void method1();
void method2();
}
interface ServiceFactory{
Service getService();
}
class Implementation1 implements Service{
private Implementation1(){}
public void method1(){System.out.println("Implementation1 method1");}
public void method2(){System.out.println("Implementation1 method2");}
public static ServiceFactory factory=new ServiceFactory(){ // 1 这里这个大括号是什么意思 为什么声明一个对象后面成跟方法体?
public Service getService(){
return new Implementation1();
}
}; //这里一定注意“;”别丢掉
}
class Implementation2 implements Service{
private Implementation2(){}
public void method1(){System.out.println("Implementation1 method1");}
public void method2(){System.out.println("Implementation1 method2");}
public static ServiceFactory factory=new ServiceFactory(){
public Service getService(){
return new Implementation2();
}
}; //这里一定注意“;”别丢掉
}
public class Factories {
public static void serviceConsumer(ServiceFactory fact){ // 2 这里的fact 是什么 后面的fact.getService();
  Service s=fact.getService(); //是怎么调用的?
s.method1();
s.method2();
}
public static void main(String[] args) {
serviceConsumer(Implementation1.factory);
serviceConsumer(Implementation2.factory);
}
}
对于这个程序的执行过我我不太明白 前两个问题不明白 还有serviceConsumer(Implementation1.factory); 这个是怎么执行的? Implementation1.factory

------解决方案--------------------
1.这里是使用一个接口,所以要实现他的方法,这里就是一个内部类,类当然要大括号来包含他其中的方法
2.fact就是ServiceFactory的啊,ServiceFactory本来就是有个getService方法的哈
3.Implementation1.factory这里就是调用Implementation1的factory这里内部类,同时给他注入到serviceConcumer,
因为如下是serviceConsumer的构造器,这里就是构造子注入
[code=Java]
public static void serviceConsumer(ServiceFactory fact){
Service s=fact.getService();
s.method1(); 
s.method2(); 
}

------解决方案--------------------
public static ServiceFactory factory=new ServiceFactory(){ // 1 这里这个大括号是什么意思 为什么声明一个对象后面成跟方法体? 
answer:这叫内部匿名类。其实是实例化了一个类(这个类实现了ServiceFactory接口,并且没有名字),因为实现了接口,当然要
有方法体来实现接口中声明的方法。又没有名字,实例化的时候就
直接用接口的名字。所以就成了上面的样子。
2、这个fact,是个形式参数,是指向ServiceFactory类型对象的一个
引用,ServiceFactory有个方法--getService(),所以可以调用。
3、Service s=fact.getService(); //调用fact的getService()方法
返回一个Service对象(这里fact看成是个工厂,产生了一个Service的对象返回了),然后有了Service的对象,就可以任意调用里面的方法了。