我有一堆派生类继承自基类。每个派生类仍然具有唯一的成员。这些派生类之一需要能够访问所有其他派生类的成员。我的目标是编写尽可能少的代码。
在基类中初始化所有派生类的成员,以便派生类之一可以访问这些成员,而不是在所述派生类中初始化它们,是草率的做法还是不好的做法?
建议的方法:
public class BaseClass {
public BaseClass() {
...
der1Initializer = Der1Initializer(new Factory1());
der2Initializer = Der1Initializer(new Factory2());
List initializers = new List(){ der1Initializer , der2Initializer };
der3Initializer = Der3Initializer(initializers);
}
Der1Initializer der1Initializer;
Der2Initializer der2Initializer;
Der3Initializer der3Initializer;
}
public class DerivedClass1 : BaseClass {
public SomeFunction {
der1Initializer.init();
}
}
public class DerivedClass2 : BaseClass {
public SomeFunction {
der2Initializer.init();
}
}
public class DerivedClass3 : BaseClass {
...
}
因此:
public class Der3Initializer {
public GroupInitializationFunction {
initializers[0].init(); //der1Initializer
initializers[1].init(); //der2Initializer
}
}
代替:
public class BaseClass {
public BaseClass() {
...
}
public class DerivedClass1 : BaseClass {
public DerivedClass1 {
der1Initializer = Der1Initializer(new Factory1());
}
public SomeFunction {
der1Initializer.init();
}
Der1Initializer der1Initializer;
}
public class DerivedClass2 : BaseClass {
public DerivedClass2 {
der2Initializer = Der2Initializer(new Factory2());
}
public SomeFunction {
der2Initializer.init();
}
Der2Initializer der2Initializer;
}
public class DerivedClass3 : BaseClass {
public DerivedClass3 {
List initializers = new List()
{
Der1Initializer(new Factory1()),
Der2Initializer(new Factory2());
};
der3Initializer = Der3Initializer(initializers);
}
...
Der3Initializer der3Initializer;
}
...
public class Der3Initializer {
public GroupInitializationFunction {
initializers[0].init(); //der1Initializer
initializers[1].init(); //der2Initializer
}
}
这是对“问题”的极大简化。该代码的目的是减少重复的代码,并减少重新初始化可以共享的成员并优化性能的需求。
我知道让其他类访问他们不使用的成员不一定是个好主意。
我只是认为这是一个有关代码分离和重复代码的有趣问题。
答案 0 :(得分:2)
我不建议将父类中的孩子初始化为
违反开放式封闭原则,因为基类有责任初始化其子级,并且始终需要添加新的子类并因此修改基类。
违反单一责任原则,因为这不是基类的角色(初始化其子级)
违反控制权反转,因为基类与子类紧密相关,请参见此link