繁体   English   中英

if语句中的多个instanceof

[英]Multiple instanceof in a if statement

我有一个if语句,其中包含多个instanceof检查。 例:

if (object instanceof Object1) {
    // do something
} else if (object instanceof Object2) {
    // to something else
} else if (object instanceof Object2) {
    // and something else
} ...

解决此if-else-query的更优雅的方法是什么?

OOP的最佳实践是将逻辑放入object本身,并使其实现接口:

界面:

public interface MyLogic{
    public void doLogic();
}

第一个对象:

public class Object1 implements MyLogic{
  public void doLogic(){// logic 1 here}
}

第二个对象:

public class Object2 implements MyLogic{
  public void doLogic(){// logic 2 here}
}

现在只需将逻辑移到对象本身,而所有if语句都将使用

object.doLogic(); // make sure object is from type MyLogic, if not, cast it

这似乎是多态的,因此您可以创建一个Interface并为每个Object实施它。

interface ObjectToBeImplemented{
 method();
}

class Object1 implements ObjectToBeImplemented{ 
 @Override
 method(){...}
}
class Object2 implements ObjectToBeImplemented{ 
 @Override
 method(){...}
}

class Object3 implements ObjectToBeImplemented{ 
 @Override
 method(){...}
}

这是接口的典型用法。 请参阅接口以定义实例的类型。 因此,您知道某个特定类型的所有实例都可以执行特定任务。 那时,您实际上并不关心对象的具体类,只知道它具有可供使用的特定接口。

范例:

public interface Worker {
     public void doWork();
}

public class Object1 implements Worker {
    public void doWork() {
      // work for this specific object
    }
}

public class Object2 implements Worker {
    public void doWork() {
      // work for this specific object
    }
}

public class Object3 implements Worker {
    public void doWork() {
      // work for this specific object
    }
}

然后,您的if语句将被替换为

obj.doWork();

感觉好像错过了多态的机会。

这是一堆类与其父类/接口共享相同方法签名的地方,因此调用它的代码不必知道它是哪种类型。

没有多态性:

Employee employee = ...;
if(employee instanceof Doctor) {
     salary = calcDoctorSalary(...);
} else if(employee instanceof Nurse) {
     salary = calcNurseSalary(...);
}

具有多态性:

Employee employee = ...;
salary = employee.calcSalary(...);

魔术进入子类。 calcSalary()是超类中的抽象,或者是接口中的方法签名:

public abstract class Employee {
     public abstract int calcSalary(...);
}

... 要么 ...

public interface Employee {
    public int calcSalary(...);
}

然后,与类型有关的逻辑进入子类:

public class Nurse implements Employee {
    @Override
    public int calcSalary(...) {
         // code specific to nurses goes here.
    }
}

您将学习经验,是扩展类还是实现接口。 通常,当人们不以某个界面开头时,便会后悔。

暂无
暂无

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

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