简体   繁体   English

同时链接多个方法调用? 提供的例子

[英]Chaining multiple Method calls at the same time? Example provided

Simply put, I have an if statement with multiple different outcomes, but a lot of code in common. 简而言之,我有一个if语句,具有多个不同的结果,但是有很多共同的代码。
I want to make sure that the following Code is the proper way to do what I'm trying to do 我想确保以下代码是执行我要执行的操作的正确方法
(ex: chaining Method calls, as shown).. is this correct? (例如:链接方法调用,如图所示).. 这正确吗?

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
}

SO - is this the correct way to go about this? 所以 -这是解决这个问题的正确方法吗?
Can I chain Method calls (as shown) and have them all fire at the same time? 我可以链接方法调用(如图所示)并使它们同时触发吗?
If not, what is the correct way to efficiently execute this? 如果没有, 有效执行此操作的正确方法是什么?
Feedback greatly appreciated! 反馈非常感谢! Thanks. 谢谢。

You can use a if block with switch inside: 您可以使用带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:
            ....
    }
}

You can also use multiple if statements instead of switch. 您也可以使用多个if语句代替switch。 The only way use can make the code more efficient is by using if (notifType != null) once. 使用可使代码更有效的唯一方法是使用一次if (notifType != null)

Assuming the code itself is inside a method you could do something like this. 假设代码本身在方法内部,则可以执行以下操作。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM