JAVA回调机制(CallBack)

时间:2022-10-06 04:37:36

http://www.importnew.com/19301.html

java 回调机制基本可以描述为: 一个类A调用另一个类B的方法,调用的同时传入必要参数及A的对象; 在B拿到其他参数并处理完后,可以把原参数和结果或其他中间值当做参数, 通过A的对象调用A的方法,这个方法我们称之为回调方法。

回调机制模板:
//实现回调的接口类 public
interface
doJob
{     public
void
fillBlank(int
a,
int b, int result);
}
//计算器公共类 public
class
SuperCalculator
{    public
void
add(int
a,
int b, doJob  customer)
    {        int
result = a + b;
        customer.fillBlank(a, b, result);    }}
//学生使用计算器 public
class
Student
{    private
String name =
null;
     public
Student(String name)
    {        // TODO Auto-generated constructor stub        this.name = name;    }     public
void
setName(String name)
    {        this.name = name;    }     public
class
doHomeWork implements doJob
    {         @Override        public
void
fillBlank(int
a,
int b, int result)
        {            // TODO Auto-generated method stub            System.out.println(name + "求助小红计算:" + a + " + " + b + " = " + result);        }     }     public
void
callHelp (int
a,
int b)
    {        new
SuperCalculator().add(a, b,
new doHomeWork());
    }}//商家使用计算器public
class
Seller
{    private
String name =
null;
     public
Seller(String name)
    {        // TODO Auto-generated constructor stub        this.name = name;    }     public
void
setName(String name)
    {        this.name = name;    }     public
class
doHomeWork implements doJob
    {         @Override        public
void
fillBlank(int
a,
int b, int result)
        {            // TODO Auto-generated method stub            System.out.println(name + "求助小红算账:" + a + " + " + b + " = " + result + "元");        }     }     public
void
callHelp (int
a,
int b)
    {        new
SuperCalculator().add(a, b,
new doHomeWork());
    }}//测试类,main方法public
class
Test
{    public
static
void main(String[] args)
    {        int
a =
56;
        int
b =
31;
        int
c =
26497;
        int
d =
11256;
        Student s1 = new Student("小明");        Seller s2 = new Seller("老婆婆");         s1.callHelp(a, b);        s2.callHelp(c, d);    }}