Java 回调(callback) 内部类(innerclass)

/**
 * 动物
 */
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,算法)