【发布时间】:2016-02-14 10:49:18
【问题描述】:
所以现在,我有一个 Preprocessor 类,它生成一堆实例变量映射,还有一个 Service 类,它有一个 setPreprocessor(Preprocessor x) 方法,所以 Service 类的实例能够访问预处理器生成的映射。
目前我的Service类需要依次调用三个方法;为了简单起见,我们称它们为executePhaseOne、executePhaseTwo 和executePhaseThree。这三个方法中的每一个都实例化/修改Service 实例变量,其中一些是指向Service 实例的Preprocessor 对象的指针。
我的代码现在有这样的结构:
Preprocessor preprocessor = new Preprocessor();
preprocessor.preprocess();
Service service = new Service();
service.setPreprocessor(preprocessor);
service.executePhaseOne();
service.executePhaseTwo();
service.executePhaseThree();
为了更好地组织我的代码,我想将每个executePhaseXXX() 调用放在它自己的Service 的单独子类中,并将所有阶段的公共数据结构保留在父类Service 中。然后,我想在Service 父类中有一个execute() 方法连续执行所有三个阶段:
class ServiceChildOne extends Service {
public void executePhaseOne() {
// Do stuff
}
}
class ServiceChildTwo extends Service {
public void executePhaseTwo() {
// Do stuff
}
}
class ServiceChildThree extends Service {
public void executePhaseThree() {
// Do stuff
}
}
编辑:
问题是,我如何在Service 父类中编写我的execute() 方法?我有:
public void execute() {
ServiceChildOne childOne = new ServiceChildOne();
ServiceChildTwo childTwo = new ServiceChildTwo();
ServiceChildThree childThree = new ServiceChildThree();
System.out.println(childOne.preprocessor); // prints null
childOne.executePhaseOne();
childOne.executePhaseTwo();
childOne.executePhaseThree();
}
但是,我的 childOne、childTwo 和 childThree 对象无法访问位于父类 Service 中的 preprocessor 实例变量...我该如何解决这个问题?
【问题讨论】:
标签: java