1 package com.test;
2 /**
3 * 回调方法的设计技巧,例如hibernate的getHibernateTemplate().execute(Handler h)方法
4 */
5 public class CallBackTest {
6 public static void main(String[] args) {
7 Service s = new Service() ;
8 //传入一个匿名的Handler实现类,重载执行的方法
9 Object object = s.getEntity(new BackHandler() {
10 @Override
11 public Object execue(Event e) {
12 return e.getName() ;
13 }
14 }) ;
15 System.out.println(object.toString());
16 }
17 }
18 //回调类的实现接口,声明回调执行的方法
19 interface BackHandler{
20 //返回的类型需要和调用的service类方法一致,传入的参数是service类方法传入
21 public Object execue(Event e) ;
22 }
23 //service类
24 class Service{
25 //传入Handler类型参数
26 public Object getEntity(BackHandler h){
27 Event e = new Event("callBack", 1) ;
28 return h.execue(e) ;
29 }
30 }
31 class Event{
32 private String name ;
33 private int status ;
34 public Event(String n,int s){
35 this.name = n ;
36 this.status = s ;
37 }
38 public String getName() {
39 return name;
40 }
41 public void setName(String name) {
42 this.name = name;
43 }
44 public int getStatus() {
45 return status;
46 }
47 public void setStatus(int status) {
48 this.status = status;
49 }
50 }