Does my example for using the Strategy design pattern with the Template Method design pattern make sense?

416 views Asked by At

For some homework, we have to devise an example (with classes) where both the Strategy and Template Method design patterns come together to complement each other and make them more customizable as a result. Or "use template method to provide more customizability to handle a variety of strategies" as it says.

After much reading and initial confusion, I came up with the idea of having two animals as classes, Dog and Snake and have them both use interfaces to implement a specific function, moving (so a dog might walk and a snake would slither). I thought this to be the Strategy pattern portion, as they're each separately implementing their own move functionality.

In order to incorporate the Template Method pattern into this, I thought I'd make it so the class it's implementing is then subclassed further for customizability, which seems to go with the question. So I thought I'd have Mover as the class and have it subclassed down into Walk and Slither. But this confused me as would each animal implement the superclass Mover, or one of the subclasses? And is the superclass Abstract, while the subclasses are Interfaces? Or are they all interfaces?

Does my example make sense?

3

There are 3 answers

0
Anupam Alok On BEST ANSWER

As Per my Understanding your example does't fit into the Strategy and Template, the Scenario best fits into Abstract Factory and May be Prototype (Depends upon full requirement). The basic difference between strategy and Template is Inheritance v/s Delegation.

If you are Searching for Strategy and template Example i would suggest you to go with some game application where the Full game can fit into template function like end of game, start the game,Winner of the game looser of the game and the Rules to play the can be fitted into Strategy like when to move, what to do with some moves.

0
Rob On

No. The main reason is because Strategy applies when you need to have different ways to do the same thing, e.g. a Layout Manager. In your example, Snakes have one way of moving, likewise Dog.

Frankly, I don't see those patterns as going together so well, not sure what the assignment is after. Template Method is great when things are done in a particular way, and variants merely implement steps of the process differently.

Probably you should think of a process where one of the steps could have a Strategy plugged in.

0
nikita On

Your example is OK if you would somehow manage to get appropriate names to BeginMove and EndMove methods in MoverStrategy.

Here:

  • GetMoveStrategy - FactoryMethod responsible for declaring interface for creation appropriate strategy
  • MoverStrategy - Strategy
  • Move - Template method with one placeholder DoMove which Concrete Strategy must define

enter image description here