[英]Chaining multiple Method calls at the same time? Example provided
简而言之,我有一个if
语句,具有多个不同的结果,但是有很多共同的代码。
我想确保以下代码是执行我要执行的操作的正确方法
(例如:链接方法调用,如图所示).. 这正确吗?
SharedPreferences getPrefs =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String notifType = getPrefs.getString
(PREF_NOTIFICATION_TYPE, NOTIFICATION_TYPE_SOUND_AND_VIBRATION);
if (notifType != null && notifType.equals
(NOTIFICATION_TYPE_SOUND_AND_VIBRATION)) {
// Call the appropriate Methods, depending on the Preference..
notificationVibration();
playNotificationTone();
showReminderNotification();
} else if (notifType !=null && notifType.equals
(NOTIFIATION_TYPE_VIBRATION_ONLY)) {
// Calling alot of the same code, but minus the Sound..
notificationVibration();
showReminderNotification();
} else if (notifType !=null && notifType.equals
(NOTIFIATION_TYPE_SILENT_REMINDER)) {
// Again re-using common code..
showReminderNotification();
}
public void notificationVibration() {
// Vibration code here
}
public void playNotificationTone() {
// Sound code here
}
public void showReminderNotification() {
// Notification code here
}
所以 -这是解决这个问题的正确方法吗?
我可以链接方法调用(如图所示)并使它们同时触发吗?
如果没有, 有效执行此操作的正确方法是什么?
反馈非常感谢! 谢谢。
您可以使用带switch
内部的if
块:
if (notifType != null) {
switch(notifType) {
case NOTIFICATION_TYPE_SOUND_AND_VIBRATION:
....
break;
case NOTIFIATION_TYPE_VIBRATION_ONLY:
....
break;
case NOTIFIATION_TYPE_SILENT_REMINDER:
....
}
}
您也可以使用多个if语句代替switch。 使用可使代码更有效的唯一方法是使用一次if (notifType != null)
。
假设代码本身在方法内部,则可以执行以下操作。
private void methodName() {
if (notifType != null)
return
switch(notifType) {
case NOTIFICATION_TYPE_SOUND_AND_VIBRATION:
....
break;
case NOTIFIATION_TYPE_VIBRATION_ONLY:
....
break;
case NOTIFIATION_TYPE_SILENT_REMINDER:
....
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.