我有以下所有其他活动扩展的类。这是一些伪代码:
public class CommonActivity extends Activity
{
//class member variables
protected void setupInterface(String activityName)
{
//a bunch of setup code here
Button select = new Button;
Button create = new Button;
Button delete = new Button;
}
protected void resetScreen()
{
selectButton.highlight();
createButton.unhighlight();
deleteButton.unhighlight();
}
}
我有五六个其他类扩展 CommonActivity,并执行以下操作:
public class SectionActivity extends CommonActivity
{
//class member variables
protected void onCreate()
{
setupInterface("sectionActivity");
}
}
现在我有另一个从 CommonActivity 扩展的 Activity,它与其他 Activity 略有不同。我发现自己正在编写以下代码:
public class ExActivity extends CommonActivity
{
//class member variables
protected void onCreate()
{
setupInterface2("sectionActivity");
}
}
然后将以下方法添加到 CommonActivity(除了已经存在的方法):
protected void setupInterface2(string activityName)
{
//a bunch of setup code here
Button select = new Button;
}
protected void resetScreen2()
{
selectButton.highlight();
}
现在我发现自己想知道消除代码重复的最佳方法。代码中的注释说“一堆设置代码”永远不会在活动之间改变。我应该在这里使用某种设计模式吗?我玩弄了模板模式的想法,但是对于 setupInterface 使用相同代码的五个类中的每一个都会在各自的类中具有重复的代码,而 ExActivity 将有自己的实现(希望这句话甚至有意义)。我也想过用 Strategy Pattern 将 setupInterface 中的唯一代码封装到自己的类中。这对我来说似乎很合理,但我觉得可能会有更优雅的东西。在这一点上,我什至认为我应该从 CommonActivity 中删除 setupInterface2 和 resetScreen2 并在 ExActivity 中简单地覆盖这些方法。这似乎是最简单的解决方案。这里的任何建议都会很棒!