简体   繁体   English

在扩展类中覆盖构造函数(Decorator模式)

[英]Overriding a Constructor in an Extended Class (Decorator Pattern)

Suppose I have a base abstract class Base that is extended by the classes Base1 , Base2 , and Base 3 . 假设我有一个基本抽象类Base ,该类由Base1Base2Base 3扩展。 It takes into its constructor an object containing information that I want to access in my decorator classes, Decorator1 and Decorator2 . 它在其构造函数中包含一个对象,该对象包含我要在装饰器类Decorator1Decorator2访问的信息。 The decorator classes extend Decorator which, in turn, extends Base . 装饰器类扩展了Decorator ,后者又扩展了Base

InfoNeeded i = new InfoNeeded(user_input);
Base a = new Base1(i);
a = new Decorator1(a);
a = new Decorator2(a);
// etc...

My issue is that I need to access i.getSomeValue1() , i.getSomeValue2() , etc... within Decorator1 and Decorator2 . 我的问题是我需要在Decorator1Decorator2访问i.getSomeValue1()i.getSomeValue2()等...。 At first I tried putting a constructor to grab i in my abstract class Base . 最初,我尝试将构造函数用于在抽象类Base抓取i Then I implemented all of my getSomeValue() functions in there so I could just call a.getSomeValue() to pull the info I need. 然后,我在那里实现了所有的getSomeValue()函数,因此我可以调用a.getSomeValue()提取所需的信息。 However, this caused issues because Decorator extends Base , forcing its constructor to take in i rather than a . 但是,这引起了问题,因为Decorator扩展了Base ,迫使其构造函数采用i而不是a

Is there a way to override the constructor in an extended class so that it's not forced to take in something I don't want? 有没有一种方法可以覆盖扩展类中的构造函数,以免被迫接受我不想要的东西?

Right now, I have my getSomeValue() functions copied and pasted among all of my base classes and decorator classes which works, but feels gross. 现在,我将getSomeValue()函数复制并粘贴到了所有有效的基类和装饰器类中,但感觉getSomeValue() I'd love to figure out a way to avoid this repetition. 我很想找出一种避免这种重复的方法。 Thanks! 谢谢!

The answer is no, you cannot override a constructor. 答案是否定的,您不能覆盖构造函数。 If the parent class needs something, you must make it available. 如果父类需要某些东西,则必须使其可用。

But, you can have more than one constructor, maybe this helps? 但是,您可以有多个构造函数,这可能有帮助吗?

On the repetition of the getSomeValue() method, could you put it in the Base class so that all the others have it? 关于getSomeValue()方法的重复,您可以将其放在Base类中,以便其他所有类都拥有它吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM