首页 > 解决方案 > 如何重构重复代码以创建 Intent?

问题描述

我主要使用不同的编程语言,但现在开始涉足 android 开发,自从我上次进行任何 java 编程以来已经有很多年了,所以我在术语上落后了很多。在我正在开发的应用程序中,有一个代码块,它在一个名为的类中看起来像这样NotificationService

Intent intent;
if (type == "1") {
  intent = new Intent(NotificationService.this, ActivityOne.class);
} else if (type == "6") {
  intent = new Intent(NotificationService.this, ActivityTwo.class);
} else {
  intent = new Intent(NotificationService.this, ActivityThree.class);
}

同一个代码块在一个活动中或多或少地重复

Intent intent;
if (type == "1") {
  intent = new Intent(ListActivity.this, ActivityOne.class);
} else if (type == "6") {
  intent = new Intent(ListActivity.this, ActivityTwo.class);
} else {
  intent = new Intent(ListActivity.this, ActivityThree.class);
}

随着 newtype的添加,我将需要维护两个 if/elseif/else 语句列表,我将如何重构它以便我可以在两个不同的地方重用相同的逻辑(一个是 NotificationSerivce,第二个是列表活动?

标签: javaandroidandroid-intent

解决方案


您可以拥有一个包含您需要的所有意图的数组:

Intent[] intents = {new Intent(), new Intent(), ...};

intent = intents[0];

推荐阅读