Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

When using the strategy pattern, is it good practice to pass this to a method on this.strategy?

I have a strategy interface with one call, TakeAction. The idea is that TakeAction decides which of the several possible actions the Client should perform and then calls the appropriate method on the client. So in a concrete strategy, the TakeAction method might look like:

void TakeAction(IAbstractClient client)
{
    if (client.IsBlah()) client.UnBlah(this.BlahValue1, this.BlahValue2);
    else if (client.CanFoo()) client.Foo(this.FooValue);
    else if (this.ShouldTwiddle()) client.Twiddle();
}

And in the client, the call looks like:

this.strategy.TakeAction(this);

Is this good form? Or is there a better way to do this? (Passing back a class with an enum describing the action and the values to pass to it seemed overkill.)

share|improve this question

1 Answer 1

up vote 4 down vote accepted

Passing this to a strategy is perfectly fine. This lets you use polymorphism as intended.

So long as the class implements the IAbstractClient interface, you are good to go.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.