我正在尝试在 Java 中实现函数对象。我有一个 Unit 类,它有一个默认的添加函数,应该在 Unit 对象的大多数初始化中使用。但是,对于某些问题,我需要不同的添加功能。代码将如下所示:
public class Unit() {
public Unit(unitType) {
if (unitType == "specialType") {
additionFunc = defaultFunc } else {
additionFunc = specialFunc }
}
}
public int swim() {
return additionFunc()
}
// definiion of regularFunc
// definition of specialFunc
}
然后,从主文件:
Unit fish = new Unit(regularTyoe);
Unit fatFish = new Unit(specialType);
fish.swim(); //regular function is called
fatFish.swim(); //special function is called
就是这样..有谁知道如何做到这一点?