我对 java +/- android 编码相对较新(旧的 C++ 编码器)。我正在构建一个应用程序,用户可以使用类似的界面处理不同的案例。答案/功能/内部运作/数字将根据情况而有所不同。
示例: 我有一个 VitalsDisplay Activity ,它应该是通用的生命体征显示代码。它想要使用函数 SetVitals(Vitals) 在显示生命体征之前修改字符串数组 Vitals。
SetVitals 必须是“智能”的 - 根据我正在处理的情况(int CaseNumber,MainActivity 中定义的公共(public) int),它将以不同的方式修改重要数组。现在,定义 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;
}
}
我不想这样做因为我担心将来的扩展 - 例如,如果我想添加额外的案例,我就必须寻找和啄食对此代码进行更改。此外,每个案例需要做的不仅仅是设置生命体征(您将订购测试等,这将必须根据案例返回不同的结果)。因此,将来扩展此功能意味着我必须搜索和啄食生命体征、结果、测试功能等。
相反,我希望定义多个 Activity :
例如,ChestPain1、ChestPain2 和 ChestPain3。每个都有一个 SetVitals(string array Vitals) 实例。它们还具有可由主 Activity 调用的 OrderResults、CaseUpdates 等实例。
此方法的问题有两个:
- 现在 switch 语句被移至 VitalsDisplay Activity/函数。这本身并不坏 - 在某些时候需要有一个 switch 语句来根据用户正在执行的 Case 来决定需要调用哪个函数。
我想知道是否有一种方法不必每次需要从唯一 Activity 中的函数(基于 CaseNumber)获取特定于案例的信息时都重新创建 switch 语句? 我尝试过基于 switch 语句创建 Intent ,然后使用 Intent 调用函数...并且失败(可能是我的错,因为我还不擅长 Intent 使用)
我也尝试过这样做:
公共(public) boolean VitalsDisplay(){ if (案件编号 == 1){
ChestPain1 CaseInfoToCall = new ChestPain1(); } else if (CaseNumber ==2){ ChestPain2 CaseInfoToCall = new ChestPain2(); } ClassInfoToCall.SetVitals(array);
//更新文本字段并显示生命体征 }
并且我收到错误:“重复的局部变量 ClassInfoToCall”。
关于如何更好地实现这一点有什么想法吗?
摘要:如何从一个 Activity 调用多个类中名称相似的函数?从哪个类调用的决定将基于 MainActivity 中设置的 int 变量。
(除非有人有更干净的方法来做到这一点 - 我也完全愿意!)
最佳答案
call the a function with the same name from different classes
您可以使这些类实现带有您要调用的方法的接口(interface)。然后,当您拥有这些类之一的实例时,您可以调用它。
更新 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();
抱歉,如果有错误,我目前没有安装 Java...
关于java - Android:如何在不使用 switch 语句的情况下从不同类调用同名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18903226/