<分区>
在最近的一次讨论中,我和一个 friend 不同意以下使用 lambda 函数来定义类功能。创建具有动态值的对象时,应该使用 lambda 传递动态值,还是使用自定义子类中的覆盖方法提供动态值?
考虑以下示例,其中的目标是拥有一个具有动态文本和图标特征的自定义标签组件。此标签必须具有方法 getText()
和 getIcon()
。以下是两个示例:一个使用多个 lambda,另一个定义子类。
Lambda 方法:
class Label {
private Supplier<String> text;
private Supplier<Image> icon;
public Label(Supplier<String> text, Supplier<Image> icon) {
this.text = text;
this.icon = icon;
}
public String getText() {
return text.get();
}
public Image getIcon() {
return icon.get();
}
}
使用:
Label timeLabel = new Label(
() -> System.currentTimeMillis(),
() -> CLOCK_IMAGE
);
子类方法:
class Label {
private String text;
private Image icon;
public Label() {
// some default
}
public Label(String text, Image icon) {
// set fields
}
// simple getters
}
使用:
class TimeLabel extends Label {
public String getText() {
return System.currentTimeMillis();
}
public Image getImage() {
return CLOCK_IMAGE;
}
}
Label timeLabel = new TimeLabel();
考虑到内部和外部开发人员的期望、可读性和可用性(包括作为 API 的类),这些方法中哪种更合适?