Java回调(钩子函数)笔记(思想)

Java回调(钩子函数):

拥有某些接口,但不关心实现,具体如何实现不详。

由实现类自己决定,相当于对外抛出一个钩子,你在上面挂什么就是什么。

具体看代码:

接口中有一个方法,传入一个字符串,实现类可以用传入的字符串做任何事情。只要传就行。

public interface HookInterface {
	
	public void whatever(String string);
	
}

A实现类

public class AImpl implements HookInterface {

	@Override
	public void whatever(String string) {
		// TODO Auto-generated method stub
		System.out.println("I am a good guy.My name is "+string);
	}

}

 A实现了hook接口,A将这个接口实现后,做了自我介绍。

B实现类

public class BImpl implements HookInterface {

	@Override
	public void whatever(String string) {
		// TODO Auto-generated method stub
		System.out.println("I hate "+string);
	}

}

 B表达了对传入字符串(人名?事务?)的不满。

就是这样的思想,我们可以继续。

这样的实现类有N多个,我们就可以做一个公共的方法。改在BImpl类,这个方法有自己的代码,唯有一处是要调用hookinterface接口的whatever方法的,这个方法同样,传什么样的hookInterface实现类就调什么样的方法。

public class BImpl {
	
	String implHook(HookInterface hi,String string){
		String myCode = "My 'hello world'!";
		hi.whatever(string);
		return myCode+"-"+string;
	}
	
	
}

测试代码:

	public static void main(String[] args) {
		
		/**
		 * A的实现
		 */
		HookInterface hi = new AImpl();
		String res = new BImpl().implHook(hi, "A");
		System.out.println(res);
		
		
//		String res = new BImpl().implHook(new HookInterface(){
//
//			@Override
//			public void whatever(String string) {
//				// 利用匿名类,写自己的实现
//				System.out.println("I'm "+string);
//			}
//			
//		}, "B");
//		
//		System.out.println(res);
		
	}

猜你喜欢

转载自vortexchoo.iteye.com/blog/2238323
今日推荐