注意:这是一个 PHP 项目
我的项目使用了 2 个 API 提供程序。 它们与它们(API)提供的信息相似。 我必须以正确的方式进行设置,因为明天可能会添加更多 API。 所以我的项目需要一些方法。 基本的,这是我到目前为止所拥有的:
abstract class A {}// first api class, mostly contains API configs and call
abstract class B {}// second api class, also mostly contains API configs and call
//than first API has a sub classes of something like cars and trucks
class Car extends A implements ApiMethodsInterface {} // for the cars
class Truck extends A implements ApiMethodsInterface {} // for the trucks
//now second API has a sub classes for cars , trucks and spaceships
class Car extends B implements ApiMethodsInterface {} // for the cars
class Truck extends B implements ApiMethodsInterface {} // the trucks
class SpaceShip extends B implements ApiMethodsInterface {} // for the space ships
//they all have more or less similar methods
// so i used an Interface that all above classes
interface ApiMethodsInterface
//methods are
public function getModels()
public function getYears()
public function getPrice()
由于每个子类都实现了这个接口,所以我按接口编码
现在,我遇到一种情况,SpaceShips 有更多方法需要添加,例如 getEquipment() 和一些更多信息,其他类未实现的方法。 Trucks 还拥有更多其他人未实现的方法,例如 hasTrailer()、trailerLength() 等。
我的问题是,现在该怎么办,我应该使用接口隔离,并将接口添加到实现这些方法的类中,然后检查实例化的对象是否具有该方法而不是运行,否则会出现一些异常,或者将缺少的模型添加到抽象类 A 和 B,并将方法重写到使用这些方法的类中,或者也许有更好的方法来解决这个问题。顺便说一句,对设计模式相当陌生,...
也许我设计过度了,但我真的想以一种好的方式做到这一点。
它可能会帮助您绘制图表,但我们可以讨论它。
接口的不同实现者拥有其他实现者没有的方法是完全正常的。接口指定所有实现者共享的方法,当您对接口进行编码时,您只需调用这些方法,而不是类也可能声明的其他方法。接口的任何实现都可以与任何其他实现互换使用。客户端不关心实现者还有哪些其他方法,它只对使用接口方法感兴趣。
但是不充当接口客户端的代码可能会以完全不同的方式查看实现。其他一些代码可能会构造一个新的 SpaceShip 并调用 getSpaceEquipment()。这也很正常。如果你构造一个新的卡车,那么你不能调用 getSpaceEquipment(),因为该类没有该方法。
将像 getSpaceEquipment() 这样的方法添加到 Truck 和 SpaceShip 都实现的接口(例如 Vehicle)中是错误的。 getSpaceEquipment() 仅对太空船有意义,不适用于所有车辆。
您可以创建一个名为 SpaceVehicle 的 Vehicle 扩展,并在其中声明 getSpaceEquipment() 方法。然后SpaceShip可以实现SpaceVehicle(这使得它通过继承也成为一个Vehicle)。但是,只有当您要拥有多个 SpaceVehicle 实现者并且需要编写与 SpaceVehicle 实例一起使用的代码,但不关心 SpaceVehicle 是 SpaceShip 还是卫星还是其他什么时,您才会这样做。