[英]Calling extended's class method from parent class with extended class keeping instances of parent's variables
I'm implementing a visitor pattern for a particular domain, where I have some BaseVisitor
, ie: 我正在为具有特定
BaseVisitor
的特定域实现访客模式,即:
public class BaseVisitor {
someC someInstance;
visitA(...) {
...
}
visitB(...) {
...
}
}
and a class that changes one particular functionality, ExtendedVisitor
, ie: 以及一个更改了特定功能的类
ExtendedVisitor
,即:
public class ExtendedVisitor extends BaseVisitor {
visitA(...) {
...
}
}
This ExtendedVisitor
has a different implementation of visitA
. 此
ExtendedVisitor
具有visitA
的不同实现。
What I want to do is that when I'm in visitB
of BaseVisitor
, in special case I want to use the method of the ExtendedVisitor
( visitA
) as opposed to the regular visitA
of the BaseVisitor
itself. 我想做的是,当我进入
visitB
的BaseVisitor
,在特殊情况下,我想使用ExtendedVisitor
( visitA
)的方法,而不是BaseVisitor
本身的常规visitA
。 This works fine, ie.: 这工作正常,即:
visitB(...) {
if (...)
new ExtendedVisitor().visitA();
else
visitA();
}
Now obviously, in the BaseVisitor
there are many visit
methods, and so the visitA
of ExtendedVisitor
will call them (ie. the original implementation of those methods - in BaseVisitor
). 现在显然,在
BaseVisitor
有许多visit
方法,因此ExtendedVisitor
的visitA
将对其进行调用(即,这些方法的原始实现-在BaseVisitor
)。 The problem is that at this point I lost the instance of someInstance
(ie. it is null
). 问题在于,此时我丢失了
someInstance
的实例(即它为null
)。 Is there a way for the two classes to share the variables? 这两个类是否可以共享变量? Ie.
就是 let the child use parent's variables?
让孩子使用父母的变量?
Since you are calling to new ExtendedVisitor() you are creating a new instance of that class and of course someInstance will be null. 由于您正在调用新的ExtendedVisitor(),因此正在创建该类的新实例,当然someInstance将为null。 You could create a constructor like
您可以创建一个类似的构造函数
public ExtendedVisitor(someC someInstance ){
this.someInstance = someInstance
}
But it doesn't sound a great idea... 但这听起来不是个好主意...
With your design you are forcing your parent class to know the functionality of its children classes. 通过您的设计,您将迫使父类了解其子类的功能。 I see a coupling issue here.
我在这里看到一个耦合问题。 Probably you should rethink your code and use inheritance and polimorfism in a better way.
可能您应该重新考虑代码,并以更好的方式使用继承和策略主义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.