vondip
vondip

Reputation: 14039

Strategy Pattern with derived alogrithms calling methods on context

I am in need for some design help. I have a class, let's call it a spaceship which can implement several behaviors. I've defined an interface to declare the operations each behavior supports. Until now this is the classic strategy pattern.

However, the implemented strategies need to be able to call actions and methods on the context class. I've been thinking of passing along the context as an interface itself to the encapsulated algorithms.

Is this the best approach? If not, what would you recommend?

enter image description here

Upvotes: 3

Views: 278

Answers (2)

Jeroen De Dauw
Jeroen De Dauw

Reputation: 10918

What you are planning to do seems fine to me. One thing to hold into account is to not pass in too much to the method(s) of your behaviour class(es). For instance, if your spaceship has an engine behaviour, only pass it your fuel tank and drive unit, not the whole spaceship.

Upvotes: 3

Tony Day
Tony Day

Reputation: 2170

Depending on what your strategies need the context for, you could consider making it event-based using the Observer pattern as well so that your strategies not coupled to the context.

An example could be if your strategies cause something in your context to change, these could be events that some intermediary (or your context itself) subscribe to.

Upvotes: 1

Related Questions