您的位置:首页 > 编程语言 > Java开发

JAVA匿名内部类实现工厂化生产

2011-09-27 20:57 232 查看
     今天看了一下内部类,发现匿名内部类貌似是一个很高深的玩意,他在初始化的时候竟然又定义了一个无名的内部类去继承这个实现类或者说是接口,可谓java实现多态性 

的一个非常漂亮的方法,下面请看实例代码

package com.bird.thinking;

/**
*
* @author Bird
* @category 匿名内部类实现工厂化生产
*/

interface Service{//需要生产的接口
void method1();
void method2();
}

interface ServiceFactory{//工厂生产接口
Service getService();
}

class Implementation1 implements Service{
private Implementation1(){}//构造器私有,禁止new

public void method1(){
System.out.println("Implementation1 method1");
}

public void method2(){
System.out.println("Implementation1 method2");
}

public static ServiceFactory factory= //使用匿名内部类实现ServiceFactory接口,将当前类初始化
new ServiceFactory(){
public Service getService(){
return new Implementation1();
}
};

}

class Implementation2 implements Service{//类似
private Implementation2(){}

public void method1(){
System.out.println("Implementation2 method1");
}

public void method2(){
System.out.println("Implementation2 method2");
}

public static ServiceFactory factory =
new 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(Implementation1.factory);//类是类的多态性

serviceConsumer(Implementation2.factory);
}
}


运行结果

Implementation1 method1
Implementation1 method2
Implementation2 method1
Implementation2 method2

     这个包里面有三个类,其实应该是五个类,因为有两个匿名内部类,他通过接口ServiceFactory实现工厂化生产,配上类继承的多态性,可以说变的太美妙的,解释在代码里面都有,还是仔细去体会代码吧。经典啊!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息