模拟父类,反向多态性
本文关键字:多态性 父类 模拟 | 更新日期: 2023-09-27 17:55:43
我已经定义了 2 个类,我们称它们为 DogActivityType
和 HorseActivityType
。它们具有相同的字段,相同的方法,但它们写入数据库中的 2 个不同的表,当然,名称也不同。
我有一个函数,所有业务规则已经适用于一个类,而另一个类使用相同的业务规则。
限制:
- 我必须使用这两个类,因为它们在项目的其他部分中使用
- 我无法创建一个类并添加另一列(字段)来区分两种类型的类。
- 我无法编辑这两个类的源代码。
.这是我的代码简化版本:
public doAllCalculations(){
// retrieve collection
foreach (DogActivityType activity in allActivities){
// a lot of code here
// more code...
createMoreOf(activity); // this is overloaded since it needs to know which DB to write to
}
}
// using overload for same function name
private createMoreOf(DogActivityType doggyActivity){
/// do some specific when it is a dog
}
private createMoreOf(HorseActivityType horse){
/// do some specific when it is a horse
}
现在的问题是:doAllCalculations()
非常广泛和复杂,在开发过程中可能会发生变化。 我不想有 2 个不同的函数(doAllCalculationsDOG()
和 doAllCalculationsHORSE()
)来进行相同的分析,只是因为我需要一个用于Dog
,另一个用于Horse
类。 有一天,项目中的某个人可能会忘记更新这两个功能或任何其他糟糕的情况......
所以,我想对两个类使用相同的函数。 因此,如果我在大计算函数中编辑规则,我将知道它适用于两个类。我想我最终会得到这样的东西:
public class AnimalActityType {
}
public doAllCalculations(){
// retrieve collection
foreach (AnimalActivityType activity in allActivities){
// a lot of code here
// more code...
createMoreOf(activity);
}
}
AnimalActityType
将模拟抽象父级,我称之为反向多态性......但是DogActityType和HorseActityType是如何知道这个父母的呢?我可以强迫父母吗?可能吗?有什么想法吗?
我无法编辑这两个类的源代码。
假设这意味着你不能为我创建一个基类甚至接口,这说明即使你想出了一个解决方案,它也只不过是一个混乱的黑客工作。我宁愿尝试找到一种绕过这种自我强加的限制的方法,而不是想出一些的多态性形式。
你可以尝试使用装饰器模式,但以非常不寻常的方式。
class Decorator
{
private object instance;
public Decprator(object instance)
{
this.instance = instance;
}
public <type> SomeCommonProp
{
get{
if(instance is DogActivityType)
{
return (instance as DogActivityType).SomeValueOrPropertyOrCall;
}
else
{
return (instance as HorseActivityType).SomeValueOrPropertyOrCall;
}
}
}
}
class MyCalculations
{
private Decorator instance;
public MyCalculations(Decorator inst)
{
instance = inst;
}
public <type> SomeCalculationMethod()
{
// here you will use instance.SomeCommonProp for your calculations
}
}