这常常出现在我身上:我有一个A类,它由B类扩展,然后有一些类派生自A类或两者(多重继承)。
示例:我有一个表示数学模型的对象,该模型定义了一个接口IModel来应用它并找到它的系数。
基于此,我推导出PolynomialModel,它定义了一大类多项式模型。
另一方面,我定义了第三个界面" IAdaptiveModel"它定义了运算符,如" +"和" - "自适应地创建模型。对于多项式模型,这将添加它们的系数。另一方面,对于神经网络来说,这没有意义。
IAdaptiveModel现在应该来自IModel(从而引起钻石问题)还是应该避免?
优点:当我对IAdaptiveModel进行运行时检查时,我可以确定它也是一个应该是的IModel。 缺点:例如PolynomialModel将继承IModel两次。
问题不针对特定的编程语言,但这里是伪代码:
classdef IModel
methods (Abstract)
y = apply(obj, x);
obj = solve(obj, x, y);
end
end
classdef IAdaptiveModel % should this derive from IModel ??
methods (Abstract)
obj = plus(obj, other);
obj = minus(obj, other);
end
end
% derives from IModel and can be used by objects requiring apply/solve
% derives from IAdaptiveModel to be used from adaptive algorithms which use plus/minus
classdef PolyModel < IBehavioralModel & IAdaptiveModel
[...]
end
% in a different piece of code in an adaptive algorithm I would have
if isa(modelObject,'IAdaptiveModel')
% technically this could fail because solve does not need to be implemented when IAdaptiveModel does not derive from IModel
modelObject = modelObject.solve(x,y);
modelObject = modelObject + const * deltaModel;
else
error('We require an object that supports IAdaptiveModel');
end