假设我有一个具有不同Scenes
的应用程序。每个场景都有一个由许多ScreenElement
构建的布局,例如将绘制到Canvas
的矩形框。对于某些Scenes
,将使用相同的框。因此,鉴于DRY,我想使用继承。
我想做的是将ScreenElement
存储在HashMap
(或最终是EnumMap
)中,以便我可以在代码的其他地方调用ScreenElement
来更改其属性。
这是我现在想出的...
这是基本布局:
Public class BasicLayout {
private HashMap<String, ScreenElement> screenElements;
public BasicLayout() {
screenElements = new HashMap<>();
screenElements.put("BACKGROUND", new ScreenElement(...));
screenElements.put("BOXONE", new ScreenElement(...));
screenElements.put("BOXTWO", new ScreenElement(...));
}
public HashMap<String, ScreenElement> getScreenElements() {
return screenElements;
}
public ScreenElement getScreenElement(String elementName) {
return screenElements.get(elementName);
}
public void draw(Canvas canvas) {
for (ScreenElement screenElement: screenElements) {
screenElement.draw(canvas);
}
}
}
然后另一种布局可能是这样的:
Public class OtherLayout extends BasicLayout {
private HashMap<String, ScreenElement> screenElements;
public OtherLayout() {
screenElements = new HashMap<>(super.getScreenElements);
screenElements.put("BOXTHREE", new ScreenElement(...));
screenElements.put("BOXFOUR", new ScreenElement(...));
}
@Override
public HashMap<String, ScreenElement> getScreenElements() {
return screenElements;
}
@Override
public ScreenElement getScreenElement(String elementName) {
return screenElements.get(elementName);
}
@Override
public void draw(Canvas canvas) {
for (ScreenElement screenElement: screenElements) {
screenElement.draw(canvas);
}
}
因此,事情是通过解决代码重复(我不再需要在
OtherLayout
中添加Background,BOXONE和BOXTWO),我介绍了代码重复!现在,我需要复制
getScreenElements
,getScreenElement
和draw
方法。在这种情况下,您需要覆盖它们,因为如果不这样做,例如getScreenElements
总是返回Background,BOXONE和BOXTWO,即使您确实需要Background,BOXONE,BOXTWO,BOXTHREE和BOXFOUR(例如在使用`OtherLayout'的Scene
。希望这是有道理的,并希望有人能提供巧妙的解决方案!
澄清:
任何时候
BasicLayout
应该具有Background,BOXONE和BOXTWOOtherLayout
在任何时候都应具有Background,BOXONE,BOXTWO,BOXTHREE和BOXFOUR。
最佳答案
这应该工作:
public class BasicLayout {
protected HashMap<String, ScreenElement> screenElements = new HashMap<>();
public BasicLayout()
{
screenElements.put("BACKGROUND", new ScreenElement(...));
screenElements.put("BOXONE", new ScreenElement(...));
screenElements.put("BOXTWO", new ScreenElement(...));
}
public HashMap<String, ScreenElement> getScreenElements() {
return screenElements;
}
public ScreenElement getScreenElement(String elementName) {
return screenElements.get(elementName);
}
public void draw(Canvas canvas) {
for (ScreenElement screenElement: screenElements) {
screenElement.draw(canvas);
}
}
}
public class OtherLayout extends BasicLayout {
public OtherLayout() {
screenElements.put("BOXTHREE", new ScreenElement(...));
screenElements.put("BOXFOUR", new ScreenElement(...));
}
}