/**
* 动物
*/
public class Animal {
private String name;
private int leg;//腿数量
private int weight;//重量
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLeg() {
return leg;
}
public void setLeg(int leg) {
this.leg = leg;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
import java.util.List;
/**
* 动物园
*/
public class Zoo {
private String name;
private List<Animal> animalList;
/**
* 统计动物的总重量
* @return
*/
public int calculateWeight(){
return calculateTotal(new CallBack(){
public int getAmount(Animal animal) {
return animal.getWeight();
}
});
}
/**
* 统计腿的数量
* @return
*/
public int calculateLegs(){
return calculateTotal(new CallBack(){
public int getAmount(Animal animal) {
return animal.getLeg();
}
});
}
/**
* 为了calculateTotal回调,写一个回调的接口,
* javascrip相对就会方便许多,不需要定义这个接口
*/
interface CallBack {
int getAmount(Animal animal);
}
/**
* 将统计的算法等装在此
* @param callBack
* @return
*/
private int calculateTotal(CallBack callBack){
int total = 0;
for (Animal animal : animalList) {
total = total + callBack.getAmount(animal);
}
return total;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Animal> getAnimalList() {
return animalList;
}
public void setAnimalList(List<Animal> animalList) {
this.animalList = animalList;
}
}
假设动物园里面有一群动物,我们要做一个统计动物的重量功能,如calculateWeight,还要做一个统计动物腿的数量的方法,其统计算法都一样,对于这种情况,就可以写一个callback,来完成。为了方便,所以直接写一个内部类接口,等java有了闭包功能,就不必多定义这个接口了:)
分享到:
相关推荐
Java中的内部类分为静态内部类(Static Inner Class)和非静态内部类(Non-static Inner Class),非静态内部类又包括成员内部类(Member Inner Class)、局部内部类(Local Inner Class)以及匿名内部类(Anonymous...
3. 内部类(Inner Class): 内部类是Java特有的特性,它定义在另一个类的内部。内部类可以访问其外部类的所有成员,包括私有成员,这使得它们成为封装和实现复杂逻辑的有效工具。内部类分为四种类型:成员内部类、...
五、内部类对象的回调机制 Java还提供了.this方式回调外围类实例,这种方法有时候十分重要。例如: ```java public class Outer { class inner { public Outer callback() { return Outer.this; } } } ``` ...
### 三、回调(Callback)机制 在RecyclerView中,我们常常需要监听列表项的操作,如点击事件。可以实现`ItemClickListener`接口,将回调方法添加到Adapter中。例如: ```kotlin interface ItemClickListener { ...
- **回调函数**:是最传统的异步编程方式,但在复杂的逻辑中容易导致回调地狱(Callback Hell)。 - **Promises**:改进了回调的问题,提供了一种更优雅的方式来处理异步操作。 - **Async/Await**:进一步简化了异步...