首页 > 解决方案 > 同时链接多个方法调用?提供的示例

问题描述

简而言之,我有一个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
}

所以- 这是解决这个问题的正确方法吗?
我可以链接方法调用(如图所示)并让它们同时触发吗?
如果不是,那么有效执行此操作的正确方法是什么?
反馈非常感谢!谢谢。

标签: javaandroidif-statementmethodssharedpreferences

解决方案


您可以使用内部的ifswitch

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。use 可以使代码更高效的唯一方法是使用if (notifType != null)一次。


推荐阅读