[英]Accessing parent class instance variables from child class instances
所以,现在,我有一个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
实例变量...我怎么能解决这个问题?
对Service
Preprocessor
实例变量使用protected
修饰符,如下所示:
public class Service {
protected Preprocessor preprocessor;
}
然后, Service
每个子类都有一个this.preprocessor
。
您的preprocessor
应受到protected
或public
,以便能够从孩子那里获得访问权限。 你可以在这里阅读修饰符。
UPDATE
new ServiceChildOne(new Preprocessor());
.....
class ServiceChildOne extends Service {
public ServiceChildOne(Preprocessor preprocessor) {
super.preprocessor = preprocessor;
}
public void executePhaseOne() {
// Do stuff
}
}
你可以在Service
类中提供一些方法,比如getPreprocessorInstance()
,它返回Preprocessor
实例
看起来您的问题是您没有一个,而是四个不同的Service
实例 - 每个实例都有自己的基类变量的未初始化副本。
我现在能想到的唯一解决方案是,首先,将服务成员变量设置为静态的相当差的设计 - 实际上,这意味着您一次只能拥有一个版本的服务。 在我看来,一个更好的解决方案是不使处理阶段成为子类,而是使它们成为以Service
实例作为参数的独立类。
编辑:举一个简单的例子, Service
类可能如下所示:
class Service
{
public Service() { ... }
public Preprocessor getPreprocessor() { ... }
public void setPreprocessor(Preprocessor preprocessor { ... }
public Type2 getVariable2() { ... }
public void setVariable2(Type2 variable2) { ... }
...
}
并且阶段类看起来像:
class ServicePhaseOne
{
private Service m_dataHost;
public ServicePhaseOne(Service dataHost)
{
m_dataHost = dataHost;
}
public void executePhaseOne()
{
// Do phase 1 stuff
}
}
...等等阶段2和阶段3。
然后execute()方法如下所示:
public void execute()
{
ServicePhaseOne phaseOne = new ServicePhaseOne(this);
ServicePhaseTwo phaseTwo = new ServicePhaseTwo(this);
ServicePhaseThree phaseThree = new ServicePhaseThree(this);
phaseOne .executePhaseOne();
phaseTwo .executePhaseTwo();
phaseThree .executePhaseThree();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.