標籤:rgs sys 執行 and 需要 hand print 類方法 callback
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 @Override11 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 }
Java回調方法的設計思路