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);
		
	}

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值