JAVA回调机制(CallBack)

来源:互联网 发布:fifa online3数据更新 编辑:程序博客网 时间:2024/05/16 10:05

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

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


回调机制模板:

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

0 0
原创粉丝点击