不访问源代码的多态行为



我希望以多态方式处理不同类型对象的多个服务的干净设计。而且,我不能访问作为服务方法参数的类的源代码。

假设这些类是CarComputer。服务PhysicalDetailsService的方法calculateWeight返回整数。每个类别的权重以不同的方式计算:

// For car
Car car = createCar();
int weight = 0;
weight += 4 * car.tierWeight
weight += frameWeight

// For computer
Computer computer = createComputer();
int weight = 0;
weight += computer.processorWeight
weight += computer.casingWeight
weight += computer.powerBankWeight

同样,CarComputer的价格可以用类似的方法计算,那么PriceService就可以用calculatePrice的方法计算了。

如何设计服务方法的参数类型,以及解决方案中的其他类型?因为我没有访问CarComputer类,我不能让他们继承/扩展一些超类/接口,如PhysicalObjectPriceHavingObject。我还应该做这样的接口,然后为汽车和电脑类型的适配器吗?有一堆ifs来检查一个对象是汽车还是电脑看起来很难看。这是抽象工厂模式创建不同类型服务的地方吗?最后,如何配置spring bean服务来解决这个问题?

您可以为每个类编写一个适配器:

interface Physical {
int getWeight();
public static wrap(Object o) {
if (o instanceOf Car car) {
return new CarWrapper(car);
} else if (o instanceof Computer computer) {
return new ComputerWrapper(computer);
} else {
throw new IllegalArgumentException(o);
}
}
}
class CarWrapper implements Physical {
private final Car car;
public CarWrapper(Car car) { this.car = car }
public int getWeight() {
return car.getTyreWeight() * 4 + car.getEngineWeight();
}
}
class ComputerWrapper implements Physical{
...
}

我不知道你关于Spring的问题是什么。

最新更新