java - 比较父类型的两个子类型时正确的 API 实现

标签 java oop design-patterns inheritance instanceof

鉴于以下情况:

public interface Vehicle {
    // Makes this vehicle race another Vehicle and returns who wins the race.
    public Vehicle race(Vehicle otherVehicle);
}

public class Car implements Vehicle {
    @Override
    public Vehicle race(Vehicle otherVehicle) {
        // Different algorithms are used to determine who wins based on
        // what type otherVehicle is.
        if(otherVehicle instanceof Car) {
            // Use algorithm #1 to determine who wins the race
        } else if(otherVehicle instanceof Helicopter) {
            // Use algorithm #2 to determine who wins the race
        } else if(otherVehicle instanceof Motorcycle) {
            // Use algorithm #3 to determine who wins the race
        }

        // ...etc.
    }
}

public class Helicopter implement Vehicle {
    @Override
    public Vehicle race(Vehicle otherVehicle) {
        // Same problem as above with Car.
    }
}

public class Motorcycle implements Vehicle {
    // ... same problem here
}

... lots of other types of Vehicles

由于使用不同的算法来比较 CarCarCarHelicopter 等,因此 race(Vehicle) 方法的实现变得难看,并且充满了 instanceof 检查......恶心。

必须有一种更加面向对象的方式来做到这一点......想法吗?

最佳答案

您可以使用double dispatch图案:

public interface Vehicle {
    // Makes this vehicle race another Vehicle and returns who wins the race.
    public Vehicle race(Vehicle otherVehicle);
    public Vehicle race(Helicopter otherVehicle);
    public Vehicle race(Motorcycle otherVehicle);
    public Vehicle race(Car otherVehicle);
}

public class Helicopter implement Vehicle {
    @Override
    public Vehicle race(Vehicle otherVehicle) {
        otherVehicle.race(this);
    }

    public Vehicle race(Helicopter heli) {

    }
    ...
}

public class Car implement Vehicle {
    @Override
    public Vehicle race(Vehicle otherVehicle) {
        otherVehicle.race(this);
    }

    public Vehicle race(Helicopter heli) {
        return heli;
    }
    ...
}


public static void Main(string args[]) {
    Vehicle car = new Car();
    Vehicle helicopter = new Helicopter();

    Vehicle winner = helicopter.race(car);
    // returns helicopter
}

关于java - 比较父类型的两个子类型时正确的 API 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20448805/

相关文章:

java - 如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?

c++ - 1 :n relation in OOP regarding to deserialisation

Javascript - 如果是异步情况

java - ImageIO 无法在 Ubuntu 上运行

java - 指定ChromeDriver运行的端口

Java Sprite 应该与 Data Structure 合并

perl - Moo 的 MooseX::NonMoose 等价物是什么?

c++ - 具有多重继承和依赖父类的设计

.net - .NET的状态机框架

java - 如何使用@JoinColumn 和@MapsId 在@OneToOne 关系中设置外键名称