简体   繁体   中英

Android: How to call a function with the same name from different classes WITHOUT using switch statements?

I'm relatively new to java +/- android coding (old C++ coder). I'm building an app where users can work through different Cases using a similar interface. The answers / functions / inner workings / numbers will be different based on case.

Example: I have a VitalsDisplay activity which is supposed to be the generic vitals display code. It wants to use a function - SetVitals(Vitals) - to modify the string array Vitals before displaying the vitals.

SetVitals has to be "smart" - based on which case I'm working on (int CaseNumber, a public int defined in the MainActivity) it will modify the vitals array in different ways. Now, the simple way to define SetVitals would be:

public static string[] SetVitals(String[] givenVitals){

  switch (MainActivity.CaseNumber){
    case 1: 
      //Change vitals in one way
      break;
    case 2:
      //Change Vitals in another way
      break;

  }
}

I don't want to do it this way because I'm worried about scaling in the future - if I want to add extra cases for example, I'd have to hunt and peck through this code to make changes. Furthermore, each case will need to do more than just set vitals (you'll order tests etc, which will have to return different results based on the case). So expanding this in the future would mean I'd have to hunt and peck through Vitals, Results, Tests functions etc.

Instead, I was hoping to define multiple activities:

ChestPain1, ChestPain2, and ChestPain3 for example. Each has an instance of SetVitals(string array Vitals). They would also have instances of OrderResults, CaseUpdates etc. that can be called by the main activity.

The problem with this method is two fold:

  1. Now the switch statement gets moved to the VitalsDisplay activity/function. This itself isn't bad - there'll need to be a switch statement at SOME point to decide which function needs to be called based on what Case the user is doing.

I was wondering if there is a way to NOT have to recreate the switch statement EVERY TIME I need to get Case Specific information from a function in a unique activity (based on CaseNumber)? I tried to create intents based on a switch statement and then use the intents to call the function... and failed (probably my fault because I'm not great at intent usage yet)

  1. I also tried to do this:

    public boolean VitalsDisplay(){ if (CaseNumber == 1){

      ChestPain1 CaseInfoToCall = new ChestPain1(); } else if (CaseNumber ==2){ ChestPain2 CaseInfoToCall = new ChestPain2(); } ClassInfoToCall.SetVitals(array); 

    //Update text fields and display vitals }

And I get an ERROR : "Duplicate local variable ClassInfoToCall".

Any ideas on how I can better implement this?

Summary : How can I from one activity call a similarly named function in multiple classes? The decision on which Class to call from will be based off an int variable set in MainActivity.

(Unless someone has a cleaner way to do this - Which I'd totally go for as well!)

call the a function with the same name from different classes

You can make that classes implement an interface with method that you want to call. Then you can call it, when you have instance of one of these classes.

Update 1

interface YourInterface {
    void DoSomething();
}

class A implements YourInterface {
    @Override
    void DoSomething() {
        // ...
    }
}

class B implements YourInterface {
    @Override
    void DoSomething() {
        // ...
    }
}

// now, somewhere else...

    YourInterface foo =
        someBooleanVariable ?
            new A() :
            new B();
    // we don't know is it an instance of A or B, but corresponding method will be called:
    foo.DoSomething();

Sorry if there's an error, I currently have no Java installed...

Here is what i did, hope it fits your need, i did it with 2 cases only, but it's the same thing for more cases :

public class MainActivity extends Activity {

    CaseWorker worker;


    Button button1;
    Button button2;


    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button)findViewById(R.id.button1);
        button2 = (Button)findViewById(R.id.button2);

        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                worker = new CaseOne();

            }
        });


        button2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                worker = new CaseTwo();

            }
        });

    }

    public void anotherMethod(String[] givenVitals){
       worker.SetVitals(givenVitals);
   }
}

Here is the CaseWorker interface, you can add to it other behaviours that are case dependent :

public interface CaseWorker {
    public  String[] SetVitals(String[] givenVitals);
}

And here are the two implementations corresponding to the two cases :

public class CaseOne implements CaseWorker {

    @Override
    public String[] SetVitals(String[] givenVitals) {
        // do the work the first way
        return null;
    }

}


public class CaseTwo implements CaseWorker {

    @Override
    public String[] SetVitals(String[] givenVitals) {
        // do the work the second way
        return null;
    }

}

You can add other buttons, and for each button you add you will have to provide another CaseWorker implementation : CaseThree, CaseFour, ... No need to switch because you're already doing it by setting the listeners to the differents buttons you have (the switch is already in the UI).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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