我在实现某些类之间的关系时遇到问题。我得到了三个不同的课程,提供三种不同的形式。所有这些类都使用同一种语言,因此它们都继承自同一个名为TAncestorServer. 让我们称其后代TForm1Server为 ,TForm2Server和TForm3Server。TAncestorServer包含一个名为Function1, so TForm1,的抽象方法TForm2,并且TForm3可以通过继承自它的自己的类毫无问题地调用它,他们可以通过名为 的属性访问这些类Server。但问题在于另一种形式,称为TForm4!它与其他形式非常相似,但不像它们那样独立。它适用于TForm2Serveror TForm3Server。仍然不是问题,但想象一下另一种方法,例如在和Function2中声明的TForm2ServerTForm3Server,TForm4需要打电话给他们。我可以这样走:
if Server is TForm2Server then
TForm2Server(Server).Function2
else if Server is TForm3Server then
TForm3Server(Server).Function2;
但它可以变成一个无限的 if-else 子句!所以我认为像多重继承这样的东西可能会有所帮助。我声明了一个名为的接口IForm4Server,其中包含Function2. 所以TForm2ServerandTForm3Server继承自TAncestorServerand IForm4Server。我认为这样的事情可以工作:
If Server is IForm4Server then
IForm4Server(Server).Function2;
但是编译器不这么认为,它说它不是有效的类型转换,因为TAncestorServeris not IForm4Server,这是绝对正确的。TForm1Server对实施一无所知Function2,必须将其留空。我也不能这样声明,因为TForm4.Server它代表了大量的方法和属性,但是我仍然不能将类型转换为.IForm4ServerFunction1IForm4ServerTAncestorServer
作为一种解决方案,我可以在TForm4like中定义两个不同的属性GeneralServer: TAncestorServer,Form4Server: IForm4Server然后为它们分配相同的TForm2Serveror实例TForm3Server,但我对此感觉不好。我该怎么做?它有什么标准模式吗?