hsz
hsz

Reputation: 152266

Decorator that covers all methods and passes automatically first parameter

I have class BaseClass that contains a few methods like

public Result mothodA(Token token, String arg1, String arg2);

public Result mothodB(Token token, String arg1);

public OtherResult mothodC(Token token, String arg1, String arg2);

...

Is it possible to decorate this class somehow to pass automatically Token argument (which will be stored in decorator) ?

Expected output:

DecoratedBaseClass decorated = new DecoratedBaseClass();
Result result = decorated.methodA("arg1", "arg2");
OtherResult otherResult = decorated.methodC("arg1", "arg2");

I bet it's not possible, but maybe I don't know about some tricks with decorators.

Upvotes: 1

Views: 1734

Answers (2)

quartzde
quartzde

Reputation: 638

You change the interface of BaseClass so this has nothing to do with decorator its more an adapter.

Decorator
Attach additional responsibilities to an object dynamically keeping the same interface.

Build a BaseClassAdapter and delegate the calls to BaseClass.

public class BaseClassAdapter {

    private final BaseClass baseClass;
    private final Token token;

    public BaseClassAdapter(BaseClass baseClass){ 
       this.baseClass = baseClass;
       this.token = ...;
    }

    public Result mothodA(String arg1, String arg2) {
       baseClass.mothodA(token, arg1, arg2);
    }

    ...
}

Upvotes: 3

dngfng
dngfng

Reputation: 1943

DecoratedBaseClass decorated = new DecoratedBaseClass(token);

Constructor in DecoratedBaseClass

//constructor in baseclass
public DecoratedBaseClass(Token token) {
    this.token = token;
}

Upvotes: 0

Related Questions