同志们,告诉我在一个体面的社会中通常如何解决这样的问题:
例如,我们有这样一个类层次结构
class A_Base
{
int x;
int y;
public A_Base(int x, int y)
{
this.x = x;
this.y = y;
}
}
class A_First : A_Base
{
string name;
public A_First(int x, int y, string name):base(x,y)
{
this.name = name;
}
}
class A_Second : A_First
{
string surname;
public A_Second(int x, int y, string name, string surname):base(x,y,name)
{
this.surname = surname;
}
}
现在我们需要向 A_Base 添加一个属性(并相应地在构造函数中对其进行初始化)
class A_Base
{
int x;
int y;
int z;
public A_Base(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
这意味着我们将不得不更改整个类层次结构中构造函数的定义,在那里添加一个新参数 z,尽管我们不更改这些构造函数本身——我们只更改对父类的调用。而且不知何故它不是很好。
class A_First : A_Base
{
string name;
public A_First(int x, int y, int z, string name):base(x,y,z)
{
this.name = name;
}
}
高级OOP的同志遇到这种情况一般是怎么操作的呢?有一个单独的类/结构将作为构造函数的参数吗?
class A_Init
{
int x;
int y;
int z;
}
class A_Base
{
int x;
int y;
int z;
public A_Base(A_Init init)
{
this.x = init.x;
this.y = init.y;
this.z = init.z;
}
}
还是有其他一些棘手的模式?