The strategy pattern defines a family of algorithms, encapsulates each one and
makes them interchangeable. This pattern allows the algorithms to vary independently
from clients that use them.
When using inheritance one often has the problem of inheriting
behaviours which are not applicable to certain derived classes.
This diagram below shows the class structure of characters within my example fighting game.
As you can see the subclasses derive the methods of the
abstract base class. In this particular
game the characters have the choice to use a range of weapons.
Now with this current class structure the weapon behaviour
is fixed, and cannot be changed at runtime.
Also with a long list of characters, each character will
need the logic in its weapon method to be added and if amendments need to be made
to a weapon then it is likely that multiple characters will have their weapon
method changed.
The strategy pattern was created to resolve these
complications and reduce time consumption.
From what has been explained previously we know that the
weapon behaviour is the behaviour that varies within the character class.
We do as the strategy pattern tells us and encapsulate the
weapon behaviour.
We do this by creating a weapon interface, and classes
(representing different weapons) that implement the weapon interface as seen
below.
We also add the “set_weapon” method to the character class.
Code
Below shows the programing implementaion of the example fighting game (described above) using the stratergy pattern.
This is our fighting game character class
This is our weapon interface
This one of our weapon classes
in the main of this example i have tried to demonstrate how assignment of the weapon assignment to characters are interchangeable.
When complied these are the results we receive
I further adapted the main program to demonstrate how a weapon can be assigned to a character at runtime, as seen below:
when complied these are the results we receive
FOR THE NEXT POST I WILL BE COVERING "THE DECORATOR PATTERN",
PLEASE STAY TUNED
No comments:
Post a Comment