简体   繁体   English

Android:如何使用switch语句从不同的类中调用具有相同名称的函数?

[英]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). 我对java +/- android编码(旧的C ++编码器)相对较新。 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. 示例:我有一个VitalsDisplay活动,该活动应该是通用的vitals显示代码。 It wants to use a function - SetVitals(Vitals) - to modify the string array Vitals before displaying the vitals. 它想使用一个函数-SetVitals(Vitals)-在显示生命体之前修改字符串数组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. SetVitals必须“智能”-基于我正在处理的情况(int CaseNumber,MainActivity中定义的公共int),它将以不同的方式修改vitals数组。 Now, the simple way to define SetVitals would be: 现在,定义SetVitals的简单方法是:

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. 因此,将来扩展此功能将意味着我将不得不通过Vitals,Results,Tests功能等来进行探索。

Instead, I was hoping to define multiple activities: 相反,我希望定义多个活动:

ChestPain1, ChestPain2, and ChestPain3 for example. 例如,ChestPain1,ChestPain2和ChestPain3。 Each has an instance of SetVitals(string array Vitals). 每个都有一个SetVitals(字符串数组Vitals)的实例。 They would also have instances of OrderResults, CaseUpdates etc. that can be called by the main activity. 他们还将具有可由主活动调用的OrderResults,CaseUpdates等实例。

The problem with this method is two fold: 此方法的问题有两个方面:

  1. Now the switch statement gets moved to the VitalsDisplay activity/function. 现在,switch语句移至VitalsDisplay活动/功能。 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. 这本身还不错,在某些时候需要有一个switch语句,以便根据用户正在执行的Case情况来决定需要调用哪个函数。

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)? 我想知道是否有一种方法不必每次都需要从唯一活动(基于CaseNumber)中的函数中获取案例特定信息时重新创建switch语句? 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) 我试图根据switch语句创建意图,然后使用意图调用该函数...并失败了(可能是我的错,因为我对意图的使用还不很熟练)

  1. I also tried to do this: 我也尝试这样做:

    public boolean VitalsDisplay(){ if (CaseNumber == 1){ 公共布尔VitalsDisplay(){如果(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". 而且我得到一个错误 :“重复的局部变量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. 调用哪个类的决定将基于MainActivity中设置的int变量。

(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 更新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... 抱歉,如果出现错误,我目前没有安装Java ...

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 : 这是我所做的,希望它能满足您的需要,我只用了2种情况,但是对于更多的情况是相同的:

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 : 这是CaseWorker界面,您可以向其中添加其他取决于大小写的行为:

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). 您可以添加其他按钮,并且添加的每个按钮都必须提供另一个CaseWorker实现:CaseThree,CaseFour,...无需切换,因为您已经通过将侦听器设置为具有的不同按钮来做到这一点(开关已在用户界面中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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