-1

I have a question regarding strategy pattern in java. In the first diagram we can see definition of the Strategy pattern. Context is composed of a Strategy interface, The context could be anything that would require changing behaviors - a class that provides sorting functionality perhaps.

The Strategy is simply implemented as an interface, so that we can swap ConcreteStrategys in and out without effecting our Context.

Normal strategy pattern Strategy pattern

Now lets look at the second diagram, . Suppose we use Strategy pattern. Classes ConcreteStrategyA and ConcreteStrategyB need to call the client to perform the algorithm they implement.

Any reason why you would need the interface Client Interface?

EliiTryToLearn
  • 125
  • 1
  • 11
  • Your concrete strategies should not be calling the client. What is the problem you want to solve? – Reasurria May 30 '18 at 05:55
  • @Reasurria yes i know that but that why i am not calling the client directly instead i am using the interface but i am wondering why I should use the interface and not call the client directly – EliiTryToLearn May 30 '18 at 15:05
  • 1
    Sorry I meant the concrete strategies are not meant to make calls to the client even through an interface. This bidirectional dependency seems strange. If you feel that is correct then there could be a few reasons for operating against the interface. For example allowing your client to be mocked during unit testing or removing a dependency on a specific client from your implementations. – Reasurria May 31 '18 at 06:04
  • "For example allowing your client to be mocked during unit testing or removing a dependency on a specific client from your implementations." @Reasurria that the answer i was looking for you can mark that as answer if u want :) – EliiTryToLearn May 31 '18 at 17:29

1 Answers1

1

You may want to operate against an interface for allowing the client to be mocked during unit testing or to remove a dependency on a specific client implementation from your concrete strategies.

Reasurria
  • 1,808
  • 16
  • 14