Java-- 匿名类

工厂方法

匿名类与正规的继承相比有些受限,因为匿名类既可以扩展类,也可以实现接口,但不能两者兼备。如果实现接口,也就只能实现一个接口。

 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 }
View Code

结果:

Implemention1 method1
Implemention1 method1
Implemention2 method1
Implemention2 method2

 

Java-- 匿名类,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。