-1

I study the strategy design pattern and from what I see, there is a very similar way to implement the "behaviors" of an object.

one way is the strategy design pattern. in this way the object 'has-a' strategy that represent the behavior.

the other way is to make this object 'implements' the behavior (interface).

for example, in a game, I have 'Enemy' object and one Enemy is flying and one is driving. so until now, I would think about: first 'Enemy' object implements Flyable and the second 'Enemy' implements Drivable. but another solution can be first Enemy 'has-a' FlyingStrategy and the second 'has-a' DrivingStrategy.

I'm trying to find the better solution in terms of good design.

Thanks.

Ori Bentov
  • 27
  • 3

1 Answers1

0

They are not interchangeable . A good example is Comparable vs Comparator in the JDK.

In your case, Comparable represents the implementing-an-interface design. Comparator is an example of the strategy pattern. With the two signatures of Collections.sort, you can do this

Collections.sort(listOfComparables);

or this

Collections.sort(anyList, comparator);

Imagine you have a list of Cars. You might want to sort the list by colour, by number of seats, by horsepower. In this case, it makes no sense to implement Comparable. Cars have no natural ordering; it makes no sense to give preference to one ordering over another by implementing the interface. In this case, all orderings are created equal. If you were to declare a car as Comparable then it would likely not be very intuitive for users of your class. They would probably have to check the implementation or the documentation to work out what order you had intended. You should sort these using Comparators.

Now imagine you have a list of Coins. Coins have a fairly obvious natural ordering: their face value. You could sort your coins by size, or by weight, but their primary reason for existing is to represent different denominations. In this case, not all orderings are created equal. It would make sense here to implement Comparable, and if other orderings are required, you can use Comparators for that.

In a more general sense, the strategy pattern is often best applied when there is no one "preferred" approach. A class can only implement an interface once, but it may be able to make use of many different strategies. It is a kind of inversion of control.

Michael
  • 41,989
  • 11
  • 82
  • 128