工厂方法
匿名类与正规的继承相比有些受限,因为匿名类既可以扩展类,也可以实现接口,但不能两者兼备。如果实现接口,也就只能实现一个接口。
1 package innerclasses; 2 3 4 interface Service{ 5 void method1(); 6 void method2(); 7 } 8 9 interface ServiceFactory{ 10 Service getService(); 11 } 12 13 class Implementation1 implements Service{ 14 private Implementation1(){} 15 public void method1(){ 16 System.out.println("Implemention1 method1"); 17 } 18 public void method2(){ 19 System.out.println("Implemention1 method1"); 20 } 21 //下面是匿名类 22 public static ServiceFactory factory = new ServiceFactory(){ 23 public Service getService(){ 24 return new Implementation1(); 25 } 26 }; 27 } 28 29 class Implementation2 implements Service{ 30 private Implementation2(){} 31 public void method1(){ 32 System.out.println("Implemention2 method1"); 33 } 34 public void method2(){ 35 System.out.println("Implemention2 method2"); 36 } 37 38 public static ServiceFactory factory = new ServiceFactory(){ 39 public Service getService(){ 40 return new Implementation2(); 41 } 42 }; 43 } 44 45 public class Factories{ 46 public static void serviceConsumer(ServiceFactory fact){ 47 Service s = fact.getService(); 48 s.method1(); 49 s.method2(); 50 } 51 public static void main(String [] args){ 52 serviceConsumer(Implementation1.factory); 53 serviceConsumer(Implementation2.factory); 54 } 55 }
结果:
Implemention1 method1
Implemention1 method1
Implemention2 method1
Implemention2 method2