Nói rằng tôi có một giao diện và một số lớp học:Java Collections: Thu thập đèo trẻ em như bộ sưu tập của cha mẹ
public interface IPanel<ComponentType extends Component> {
public void addComponents(Set<ComponentType> components);
public ComponentType create();
}
public class Button extends Component { }
public class LocalizedButton extends Button { }
public class ButtonsPanel implements IPanel<Button> {
public void addComponents(Set<Button> components) { ... /* uses create() */ ; }
public Button create() { return new Button(); }
}
public class LocalizedButtonsPanel extends ButtonsPanel {
public Button create() { return new LocalizedButton(); }
}
Sau đó, tôi có một bộ LocalizedButtons và khi tôi gọi
final LocalizedButtonsPanel localizedButtonsPanel = new LocalizedButtonsPanel();
final Set<LocalizedButton> localizedButtonsSet = new LinkedHashSet<LocalizedButton>();
localizedButtonsPanel.addComponents(localizedButtonsSet);
tôi nhận được rằng phương thức này không áp dụng cho các đối số này. Nếu tôi cố gắng quá tải phương pháp này là addComponents(Set<LocalizedButton> buttons)
trong LocalizedButtonsPanel
, tôi sẽ xóa được loại, tất nhiên.
Có thể một số mẫu bị bỏ qua hoặc thủ thuật tồn tại để đối phó với kiến trúc này để thực hiện chính xác việc thêm tập hợp LocalizedButtons?
Tôi đã có câu trả lời và tôi muốn thực hiện ví dụ của tôi cụ thể hơn - Tôi có một số xác nhận trong việc thực hiện của tôi, vì vậy tôi cần phải loại bộ sưu tập để cũng được lưu trữ như chung, đó là đơn giản hóa mã tôi đã có sử dụng câu trả lời:
public interface IPanel<ComponentType extends Component, CollectionType extends Collection<? extends Component>> extends Validated<CollectionType> {
public void addComponents(CollectionType components);
public ComponentType create();
}
public class Button extends Component { }
public class LocalizedButton extends Button { }
public class ButtonsPanel implements IPanel<Button, Set<? extends Button>> {
public void addComponents(Set<? extends Button> components) { ... /* uses create() */ ; }
public Button create() { return new Button(); }
}
public class LocalizedButtonsPanel extends ButtonsPanel {
public Button create() { return new LocalizedButton(); }
}
Và trong trường hợp này, nó hoạt động
có (có thể là) một câu hỏi tương tự http://stackoverflow.com/questions/298305/, nhưng câu trả lời có phá vỡ giao diện tôi có –