首页 > 编程语言 > 详细

Java-- 匿名类

时间:2014-06-21 09:08:47      阅读:268      评论:0      收藏:0      [点我收藏+]

工厂方法

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

bubuko.com,布布扣
 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-- 匿名类,布布扣,bubuko.com

Java-- 匿名类

原文:http://www.cnblogs.com/fxyfirst/p/3795147.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!