Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Decorator Pattern: Can I decorate a protected method?

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(){...}
}

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
}

Is there some solution for this challenge?

like image 297
David Parks Avatar asked Apr 21 '11 10:04

David Parks


1 Answers

If you put AbstractActor and ActorDecorator in the same package, you will be able to access the protected method.

like image 50
darioo Avatar answered Oct 31 '22 23:10

darioo