Java Decorator Pattern: can I decorate a protected method?

I want to decorate (Decorator design template) a common base class, but the method I need is protected. Example:

public class AbstractActor {
   public void act(){...}      //Delegates its actions to doAct() based on some internal logic
   protected void doAct(){...}
}

Subclasses are designed to override doAct (), I need to add some functions there. I can override doAct, but my decorator class cannot access the protected doAct () method on the decorated instance. 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 any solution for this?

+5
source share
4 answers

If you put AbstractActor, and ActorDecoratorin the same package, you'll be able to access a protected method.

+6
source

, , , ( ), ? :

public class ToDecorateActor extends AbstractActor {
 public void publicAct() {
  doAct();
 }
}

public class ActorDecorator {
   ToDecorateActor decoratedInstance;
   public ActorDecorator(ToDecorateActor decoratedInstance){
      this.decoratedInstance = decoratedInstance;
   }
   protected void doAct(){
      //Inject my code
      decoratedInstance.publicAct();
   }
   //Other decorator methods
}
0

, - , , , .

- (AOP, AspectJ, ), doAct(). Spring AOP-, .

, .

0

When a class developer saves a protected method, it must remain so! If you break encapsulation in this way, then this creates a very bad programming example for everyone and more problems for class consumers.

Having said that, in your case, what prevents you from entering the code in the call to override [t20>? What invokes your protected method doAct()anyway?

Hope this helps.

-1
source

All Articles