今天看了一下内部类,发现匿名内部类貌似是一个很高深的玩意,他在初始化的时候竟然又定义了一个无名的内部类去继承这个实现类或者说是接口,可谓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