【发布时间】:2020-06-13 14:58:57
【问题描述】:
public class Decorator : ICommonInterface
{
ComponentType baseRef {get; set;}
ComponentFunction //Function that i want to modify with the Decorator
{
//Additional stuff i want to do here
baseRef.ComponentFunction() // do stuff
}
}
public class DecoratedClass : ICommonInterface
{
ComponentFunction(){ //do stuff }
}
这几乎就是我定义我的装饰器的方式。我就是这样用的:
main(){
DecoratedClass _base = new DecoratedClass();
Decorator _end = new Decorator(_base);
_end.ComponentFunction() // I use the Decorator _end ComponentFunction instead of
// doing _base = new Decorator(_base) so i keep base reference
}
但在 main 内部的某个时间点,我必须执行以下操作:
main(){
// some point later inside main
_base = new ClassThatInheritsFromDecoratedClass()
}
我仍将使用 _end 变量来调用 ComponentFunction(),但 _end 具有旧的 _base 值。 在 C/C++ 中,我可以使用指针而不是使用 new 关键字来重新定义 _base 或其他东西,但是是否可以像在 C# 中那样更改 _base 并且 _end.baseRef 是 _base 的新值而不做类似的事情:
_end.baseRef = _base
在我用 new 关键字更改 _base 之后?
【问题讨论】:
-
我过度简化了一些东西,没有很长的文本,但为了解释更多,有两个不同的系统与组件交互:一个向组件添加装饰器,另一个直接在某些组件中更改它方式(某些方式会改变_base)。因此,如果 _end 保留 base 的新值,就像我说的 C/C++ 中的指针一样,就没有必要为系统之间的交互编写复杂的中介模式。此外,它是针对游戏的,因此这些更改可能会在游戏循环中随机发生
-
您能否解释一下为什么在更改
_base后无法设置_end = new Decorator(_base)? -
目前的实现方式不允许这样做。就像我说的,这是两个完全不同的系统,它们以不同的方式更改组件(_base)。一个添加装饰器,然后使用装饰器(_end 是堆栈上的最后一个装饰器)和其他更改 _base 直接,永久。如果在这个其他系统上更改 _base “更新” _end 对 _base 的引用,就像我可以在 C/C++ 中使用指针和地址一样,这将使我的生活变得更加简单,因为没有必要为这两个系统编写复杂的中介类系统。