假设我有两种方法void chargeToIndividual(int amount, int account)
和void chargeToCompany(int amount, int account)
。假设我有另一个名为void processSale(String item, Customer c)
的方法。我该怎么办?我可以将chargeToIndividual
或chargeToCompany
作为processSale
的参数传递给我,我该怎么称呼它?
例如我希望能够做到
if(isIndividual(someCustomer))
{
processSale(anItem, someCustomer, chargeToIndividual)
}
else if(isCompany(someCustomer))
{
processSale(anItem, someCustomer, chargeToCustomer)
}
在processSale()
内,我如何实际致电chargeToIndividual
或chargeToCustomer()
?
答案 0 :(得分:2)
您有两个功能:
void chargeToIndividual(int amount, int account);
void chargeToCompany(int amount, int account);
他们的共同点是,他们都采用两个int
参数并返回void
。 java.util.function
中没有与此形状匹配的功能界面。但是很容易定义我们自己的:
interface IntIntConsumer {
void accept(int amount, int account);
}
您将按如下方式重写调用代码:
if (isIndividual(someCustomer)) {
processSale(anItem, someCustomer, MyClass::chargeToIndividual);
} else if (isCompany(someCustomer)) {
processSale(anItem, someCustomer, MyClass::chargeToCompany);
} else { ... }
如果chargeToIndividual
和chargeToCustomer
是实例方法,则可以使用this::chargeToIndividual
和this::chargeToCustomer
。另一种方法是将充电功能存储在局部变量中。然后,您只需拨打processSale
一次电话:
IntIntConsumer chargeFunc;
if (isIndividual(someCustomer)) {
chargeFunc = this::chargeToIndividual;
} else if (isCompany(someCustomer)) {
chargeFunc = this::chargeToCompany;
} else { ... }
processSale(anItem, someCustomer, chargeFunc);
现在在processSale
中,对充电功能的调用将如下所示:
void processSale(Item item, Customer customer, IntIntConsumer func) {
...
func.accept(item.getAmount(), customer.getAccount());
...
}
当然,我已经假设了amount
和account
参数的位置,但我认为你可以理解。
答案 1 :(得分:0)
因为问题是关于使用lambdas:
import java.util.function.Consumer;
public class PlayWithLambdas {
public void testIsCustomer(Consumer<Chargeable> f) {
Chargeable customer = new Customer();
Chargeable company = new Company();
f.accept(customer); // prints "true"
f.accept(company); // prints "false"
}
public static void main(String[] args) {
PlayWithLambdas p = new PlayWithLambdas();
p.testIsCustomer(chargeable -> {
System.out.println(chargeable.getType().equals(ChargeableType.CUSTOMER));
});
}
}
interface Chargeable {
public ChargeableType getType();
}
class Customer implements Chargeable {
@Override
public ChargeableType getType() {
return ChargeableType.CUSTOMER;
}
}
class Company implements Chargeable {
@Override
public ChargeableType getType() {
return ChargeableType.COMPANY;
}
}
enum ChargeableType {
CUSTOMER, COMPANY;
}
我希望这位没有任何意义的可怜作家能够帮助你:)