java - 如何重构重复代码以创建 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,第二个是列表活动?
解决方案
您可以拥有一个包含您需要的所有意图的数组:
Intent[] intents = {new Intent(), new Intent(), ...};
intent = intents[0];
推荐阅读
- java - 如何从 Matcher 获取视图
- javascript - 最大素数函数工作太慢
- geojson - Mapbox GL JS:带有外部 JSON 的弹出 onclick
- android - 我们如何在 UI 线程中创建处理程序以将数据发送到另一个线程
- c# - HttpWebRequest 请求被中止:操作已超时
- google-apps-script - 在 Google 脚本中将 HTML 转换为纯文本
- python - Pandas to PySpark:将一列元组列表转换为每个元组项的单独列
- java - 使用抽象参数调用 Java 泛型接口
- javascript - 如何从 javascript 在 div 中插入元素?
- php - 使用 ajax 选项卡加载发布表单