有谁能帮助一位初学者程序员理解他的解决方案是否正确?
我的问题类似于以下两个问题:
问题:我想要有子类,这些子类仅在其初始化方法中有所不同。但是,我还想防止在没有初始化的情况下实例化这些类。换句话说,我想确保在子类实例化后总是会调用某些“initialize()”方法:
public abstract class Data {
protected Parameter dataSource;
Data(parameter1){
this.dataSource = parameter1;
loadData(); // should be called to initialise class fields and ensure correct work of other class methods
}
protected abstract loadData(){
... //uses dataSource
}
}
所以我决定在构造函数中执行初始化。这行得通(现在我知道这是一种非常不好的做法),直到我创建了一个子类,其中initialize方法使用了一些额外的参数:
public class DataFromSpecificSources extends Data {
private Parameter dataSource2;
public DataFromSpecificSources(parameter1, parameter2){
this.dataSource2 = parameter2; // I can't put it here because the constructor is not called yet
super(parameter1); // this, of course, will not work
}
@Override
private void loadData(){
... // uses both dataSource 1 and 2
// or just dataSource2
}
}
当然,这样做是行不通的。于是我开始寻找正确的模式……在阅读之前发布的问题答案后,我决定使用工厂并将子类构造函数的可见性限制为包内: 我的解决方案:
// factory ensures that loadData() method will be called
public class MyDataFactory(){
public Data createSubClass(parameter1,parameter2){
Data subClass;
if (parameter2 != null){
subClass = new DataFromSpecificSources(parameter1, parameter2);
subClass.loadData();
} else {
subClass = new AnotherSubClass(parameter1);
subClass.loadData()
}
return subClass;
}
}
public abstract class Data {
protected Parameter dataSource;
Data(parameter1){
this.dataSource = parameter1;
}
// I don't call it in constructor anymore - instead it's controlled within the factory
protected abstract loadData(){
... //uses dataSource
}
}
public class DataFromSpecificSources {
private Parameter dataSource2;
protected DataFromSpecificSources(){}
// now this constructor is only visible within package (only for the factory in the same package)
DataFromSpecificSources(parameter1, parameter2){
super(parameter1); // it does not initialise data anymore
this.dataSource2 = parameter2;
}
@Override
protected void loadData(){
... // uses dataSources 1 and 2
}
}
现在工厂确保了子类的初始化(数据将被加载),并且不允许在其他包中实例化子类。其他类无法访问子类的构造函数,被强制使用工厂获取子类的实例。
我想问一下我的解决方案是否正确(逻辑上),并且用子类构造函数可视性限于包的工厂方法是正确的选择?还是有其他更有效的模式来解决这个问题?!
Data
中的静态方法吗? - John B