假設我有一個基類摘要類Base
,該類被Base1
,Base2
和Base 3
類擴展。它在構造函數中包含一個對象,其中包含我想要在我的裝飾器類Decorator1
和Decorator2
中訪問的信息。裝飾類擴展Decorator
,而這又擴展了Base
。在擴展類(裝飾器模式)中重寫構造函數
InfoNeeded i = new InfoNeeded(user_input);
Base a = new Base1(i);
a = new Decorator1(a);
a = new Decorator2(a);
// etc...
我的問題是,我需要訪問i.getSomeValue1()
,i.getSomeValue2()
,等...內Decorator1
和Decorator2
。起初,我試着讓我的抽象類Base
中的構造函數抓取i
。然後我在那裏實現了我所有的getSomeValue()
函數,所以我可以撥打a.getSomeValue()
來提取我需要的信息。但是,這導致問題,因爲Decorator
延伸Base
,迫使其構造函數採取i
而不是a
。
有沒有辦法覆蓋的構造函數中的擴展類,因此,它不是被迫採取的東西,我不想要的嗎?
現在,我有我的getSomeValue()
功能複製並在所有我的基類和工程類裝飾貼的,但感覺噁心。我很想找出避免這種重複的方法。謝謝!