JAVA匿名内部类实现工厂化生产
2011-09-27 20:57
253 查看
今天看了一下内部类,发现匿名内部类貌似是一个很高深的玩意,他在初始化的时候竟然又定义了一个无名的内部类去继承这个实现类或者说是接口,可谓java实现多态性
的一个非常漂亮的方法,下面请看实例代码
运行结果
这个包里面有三个类,其实应该是五个类,因为有两个匿名内部类,他通过接口ServiceFactory实现工厂化生产,配上类继承的多态性,可以说变的太美妙的,解释在代码里面都有,还是仔细去体会代码吧。经典啊!!!
的一个非常漂亮的方法,下面请看实例代码
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实现工厂化生产,配上类继承的多态性,可以说变的太美妙的,解释在代码里面都有,还是仔细去体会代码吧。经典啊!!!
相关文章推荐
- JAVA匿名内部类实现工厂化生产
- java回调及匿名内部类实现
- java匿名内部类实现工厂设计方法
- 匿名内部类是否可以继承其它类是否可以实现接口 _JAVA面试题及答案
- java中匿名内部类的两种实现方式
- Java - Anonymous Inner Class(匿名内部类)是否可以继承其它类?是否可以实现接口?
- 转.java中匿名内部类的两种实现方式
- Java中用匿名内部类实现实例化抽象类
- Exception in thread "main" java.lang.ClassCastException: $Proxy0 利用匿名内部类创建InvocationHandler接口实现
- java中匿名内部类的两种实现方式 (引用)
- Java实现匿名内部类的简单应用
- Java匿名内部类继承类和实现接口
- [置顶]Java中 实现多线程成的三种方式(继承,实现,匿名内部类)
- 【Java面试题】13 Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)?
- 文章标题 java匿名内部类的实现
- Anonymous Inner Class(匿名内部类)是否可以继承其它类?是否可以实现接口?【Java面试题】
- Java多线程 匿名内部类实现多线程
- c#中类似JAVA中匿名内部类实现
- Java中用匿名内部类实现实例化抽象类
- Java_基础—多线程(匿名内部类实现线程的两种方式和设置名字的方法)