我想在循环浏览设备列表时调用删除功能。这些设备可以是两种类型之一 - SmsPhone或Email。这可以通过Java 8 FunctionalInterfaces之一来实现吗?
// leaving out implementation details for simplicity
public class SmsPhone extends Device {
}
public class Email extends Device {
}
public class Device {
private String contact;
public String getContact() { return contact; }
public void setContact(String contact) { this.contact = contact; }
}
public class MyService {
public void updateEmail(String username, Collection<Email> allEmails, Collection<String> selectedEmails) {
updateUserDevices(username, allEmails, selectedEmails);
}
public void updateSms(String username, Collection<SmsPhone> allPhones, Collection<String> selectedPhones) {
updateUserDevices(username, allPhones, selectedPhones);
}
private void updateUserDevices(final String username, Collection<Device> devices, Collection<String> contacts) {
// put all the device contact info in the list and then filter out the ones in the given devices collection.
devices.stream()
.map(d -> d.getContact())
.filter(s -> !contacts.contains(s))
.forEach(s -> /***Call either deleteEmail() or deleteSms()***/);
}
private void deleteEmail(String email) {}
private void deleteSms(String sms) {}
}
答案 0 :(得分:0)
尝试
private void updateUserDevices(final String username, Collection<Device> devices, Collection<String> contacts) {
// put all the device contact info in the list and then filter out the ones in the given devices collection.
devices.stream()
.filter(d -> !contacts.contains(d.getContact()))
.forEach(MyService::delete);
}
private void delete(Device d) {
String contact = d.getContact();
if (d.isEmail()) {
deleteEmail(contact);
} else {
deleteSms(contact);
}
}
private void deleteEmail(String email) {}
private void deleteSms(String sms) {}
答案 1 :(得分:0)
你应该使用抽象的Device
方法使delete
成为一个抽象类:
public abstract class Device {
private String contact;
public String getContact() { return contact; }
public void setContact(String contact) { this.contact = contact; }
public abstract void delete();
}
通过这种方式,您可以在任何delete
上调用Device
,而不知道其类型,Device
的每个子类都可以按照自己的方式实现delete
。