回调函数理解的小例子

1.回调的理解:

public class ShowResult implements ShowImplements {
	public static void main(String[] args) {
		ShowResult showResult = new ShowResult();
		String input = "8 * 9";
		CountMethod countMethod = new CountMethod();
		// 调用getResult作运算,然后回调在回调方法里显示结果
		countMethod.getResult(input, showResult);
	}

	/**
	 * 回调此方法
	 */
	@Override
	public void showResult(String input, int result) {
		System.out.println("计算:" + input + ";结果为:" + result);
	}
}
public class CountMethod {
	
	public void getResult(String input, ShowResult showResult) {
		int result = 0;
		String[] param = input.split(" ");
		int a = Integer.parseInt(param[0]);
		String symbol = param[1];
		int b = Integer.parseInt(param[2]);
		
		if ("+".equals(symbol)) {
			result = a + b;
		} else if ("-".equals(symbol)) {
			result = a - b;
		} else if ("*".equals(symbol)) {
			result = a * b;
		} else if ("/".equals(symbol)) {
			result = a / b;
		}
		// 回调显示运算结果
		showResult.showResult(input, result);
	
	}

}

2.真正的用法是通过接口来使用

public interface ShowImplements {
	
	void showResult(String input, int result);

}

public class ShowResult implements ShowImplements {
	
	public static void main(String[] args) {
		
		ShowResult showResult = new ShowResult();
		String input = "8 * 9";
		CountMethod countMethod = new CountMethod();
		
		countMethod.getResult(input, showResult);
		
	}

	/**
	 * 回调方法
	 */
	@Override
	public void showResult(String input, int result) {
		System.out.println("计算:" + input + ";结果为:" + result);
	}

}

public class CountMethod {
	
	public void getResult(String input, ShowImplements someone) {
		int result = 0;
		String[] param = input.split(" ");
		int a = Integer.parseInt(param[0]);
		String symbol = param[1];
		int b = Integer.parseInt(param[2]);
		
		if ("+".equals(symbol)) {
			result = a + b;
		} else if ("-".equals(symbol)) {
			result = a - b;
		} else if ("*".equals(symbol)) {
			result = a * b;
		} else if ("/".equals(symbol)) {
			result = a / b;
		}
		// 回调显示运算结果
		someone.showResult(input, result);
	
	}

}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值