In my previous question, I've been taught that the below code is an example of the Strategy Pattern. The line _player.Draw(spriteBatch, _context);
in particular.
I don't see the difference between that line and the one below it, aside from the former being an extra method call.
Could someone explain me why I wouldn't just use the second call right to the _drawHugeContext
and (gasp) delete Draw()
from the Player
class? Is this example too simple and is there a situation where the former would be much better?
public class Arena
{
Player _player;
IPlayerContext _drawHugeContext;
public void Draw(SpriteBatch spriteBatch)
{
_player.Draw(spriteBatch, _drawHugeContext);
_drawHugeContext.Draw(spriteBatch, _player);
}
}
public class Player
{
public int Percentage { get; private set; }
[...] //A few more fields
public void Draw(SpriteBatch spriteBatch, IPlayerContext context)
{
context.Draw(spriteBatch, this);
}
}
public class IPlayerContext
{
public void Draw(SpriteBatch spriteBatch, Player player)
{
spriteBatch.Draw(player.Percentage);
[...] //A few more fields drawn from player
}
}
You are using strategy patterns, but probably you do not yet understand why and how to use them. Let me give you a very simple example.
Let's say you have a set of objects and you want to sort them. The problem is: how do you specify the sort order? In .Net this is typically done by passing a lambda or a class which knows how to compare two of those objects to the "Sort" method, e.g.
var sorted = MyObjects.Sort((a,b) => a.Id > b.Id);
This allows you to decouple the logic of how to generically sort a list to the logic of how to order two elements of a specific set.
In your case SpriteBatch
is the strategy that is injected in the calls, so that your object structure does not need to know, exactly, how to draw stuff.
I think you can use the example above to restructure your code effectively.