本文介绍了Java Decorator模式:我可以装饰一个受保护的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要装饰(装饰设计模式)一个普通的基类,但是我需要装饰的方法是受保护的。参见示例:
I want to Decorate (Decorator design pattern) a common base class, but the method I need to Decorate is protected. See example:
public class AbstractActor {
public void act(){...} //Delegates its actions to doAct() based on some internal logic
protected void doAct(){...}
}
子类旨在覆盖doAct(),我需要注入一些功能。我可以覆盖doAct,但是我的装饰器类无法访问正在装饰的实例上的受保护方法doAct()。示例:
Subclasses are meant to override doAct(), I need to inject some functionality there. I can override doAct, but my decorator class can't access the protected method doAct() on the instance being decorated. Example:
public class ActorDecorator extends AbstractActor {
AbstractActor decoratedInstance;
public ActorDecorator(AbstractActor decoratedInstance){
this.decoratedInstance = decoratedInstance;
}
protected void doAct(){
//Inject my code
decoratedInstance.doAct(); //Can't call protected method of decoratedInstance
}
//Other decorator methods
}
有没有解决这个难题?
推荐答案
如果你把在同一个包中的AbstractActor
和 ActorDecorator
,您将可以访问受保护的方法。
If you put AbstractActor
and ActorDecorator
in the same package, you will be able to access the protected method.
这篇关于Java Decorator模式:我可以装饰一个受保护的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!