Jump to content
  • Advertisement
Sign in to follow this  
Alpha_ProgDes

Strategy pattern.... am I on the right track?

This topic is 2133 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

So based on the code in this thread, I've implemented a very simple Strategy pattern. Well I think I did. Basically, is it good, bad, completely off the mark?

Strategy code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DesignPatterns
{
    class Strategy
    {
    }

    public interface IAdd
    {
        int moveXUnits(int XUnits);
    }

    public abstract class Movement : IAdd
    {
        private int startUnit;
        private int stepUnits;
        private int totalSteps;

        public Movement()
        {
            startUnit = 0;
            stepUnits = 1;
            totalSteps = 0;
        }

        public Movement(int initializeUnit, int initializeStep)
        {
            startUnit = initializeUnit;
            stepUnits = initializeStep;
            totalSteps = startUnit;
        }

        public int moveXUnits(int XUnits)
        {
            stepUnits = XUnits;
            totalSteps += stepUnits;
            return totalSteps;
        }

        private int autoMoveXUnits()
        {
            totalSteps += stepUnits;
            return totalSteps;
        }

        public virtual void Step(int XUnits)
        {
            moveXUnits(XUnits);
        }

        public virtual void Step()
        {
            autoMoveXUnits();
        }

        public virtual void displaySteps()
        {
            Console.WriteLine("I have moved " + totalSteps.ToString() + " units.");
        }
    }

    public class Walk : Movement
    {
        public Walk() : base(1,2){}
    }

    public class Skip : Movement
    {
        public Skip() : base(2,3){}
    }

    public class Run : Movement
    {
        public Run() : base(3,5){}
    }

    public class Character
    {
        private Movement movememtAction;

        public Character()
        {
            movememtAction = new Walk();
        }

        public Character(Movement initMovement)
        {
            movememtAction = initMovement;
        }

        public void setMovement(Movement movementToPerform)
        {
            movememtAction = movementToPerform;
        }

        public void Step()
        {
            movememtAction.Step();
        }

        public void Step(int newSteps)
        {
            movememtAction.Step(newSteps);
        }

        public void displaySteps()
        {
            movememtAction.displaySteps();
        }
    }
}

Main.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns
{
    class Program
    {
        static void Main(string[] args)
        {
            Character Mario = new Character(new Run());
            Character Link = new Character(new Walk());
            Character Zelda = new Character(new Skip());

            Mario.Step();
            Mario.displaySteps();
        }
    }
}
Edited by Alpha_ProgDes

Share this post


Link to post
Share on other sites
Advertisement

Where is your override keyword? To realize Polymorphism, you have to implement 3 conditions:

1. Contains inheritance.(Interface or base class)

2. Contains override(use abstract/override or virtual/override or realize the interface method)

3. Mutiple base class objects which point to a derived class reference.

 

You should use override keyword in your derived class to replace the behavior of base class. Otherwise you should use new keyword to prevent derived class to replace the method of base class.

Share this post


Link to post
Share on other sites
Guest Hiwas
Beyond the code in general, I suspect there is a disconnect in the intention of the strategy pattern here as I mentioned in our chat. What are you changing based on the "strategy" here? The only things being changed are two member values, that is simple C++ initialization pattern and not something you use the "strategy" pattern for.

While there is nothing wrong with your implementation after the fixes, there is still a fundamental issue that this is not the intention of the strategy pattern as described by the GOF design patterns book. Given this code, you have implemented a single strategy: "GroundMovement", the changes in values don't change the strategy and are simply initialization values. To make this an actual strategy, you might add "AirMovement" which calculates gravity effect on the movement algorithm, so the actual code for "moveXUnits" changes between the strategies. The intention of the strategies is to insert new code to change the fundamental behavior of certain common calls, not to simply change some values here and there because that is covered in the non-book design pattern of simple C++.

Hopefully this is helpful. I'm not trying to be an ass, but using patterns means using them for the correct reasons, without that proper application you are writing overly complicated code for no good reason but calling it a pattern not intended for this problem. This leads to confusion and poor code in the long run I'm sorry to say.. Edited by Hiwas

Share this post


Link to post
Share on other sites
Regarding the strategy, movement is clearly far more complex than counting steps. You should think of extracting interchangeable strategies only after you have multiple kinds of units and multiple kinds of movement; as AllEightUp explains, what you have now is only a draft of a couple of simple unit stats.

Share this post


Link to post
Share on other sites

The high level view of the strategy pattern is that the interface to a behavior never changes but the behavior itself changes.  

 

A simple example might be a convex hull strategy pattern.  There are probably 10 different ways to solve the convex hull pattern.  Some perform better than others depending on the type of data that's input to the pattern.  If you need to do convex hull solutions frequently and you monitor data input patterns that you are receiving, you might decide that a different algorithm for the convex hull is more appropriate.  Rather than placing a series of 'if-thens' that surround each convex hull algorithm you can simply have your interface point to the best algorithm.

 

I realize the convex hull solution is a fairly simple example.  You don't really need much more than an 'execute' method, although if you could customize sub-steps that have a common interface it would start to get some benefit.

 

Let's take your example.  Maybe a certain class of creatures implement methods to listen(), assess_opponent(Creature &), look(), attack(Creature &), flee(), etc.  You could have a generalized opponent interaction function that does something like:

if( listen() == OPPONENT_DETECTED )
{
   Creature& opponent = get_detected_opponent();
   bool we_do_attack = assess_opponent(opponent);
   if( we_do_attack )
    {
        attack(opponent);
    }
   else
    {
        flee();
    }
}

You could have a strategy pattern that provides interfaces to those methods with a possible default behavior.  You can then provide a way to change the underlying strategies at run time (this is a crucial difference from the template pattern which chooses behavior at compile time).  For example, maybe your creature has super ears that can echo locate creatures, but somewhere in the course of the game it sustains an injury that renders it stone deaf.  Rather than provide a series of 'if-thens' in the above code, you could change your strategy that implements a 'deaf' version of listen().

 

Essentially what this buys you is the ability to have code that has the same overall logic but lets you vary behavior dramatically.  It saves you from having to change the above code constantly despite changes in underlying behavior, which is really one of the major benefits of design patterns.

Edited by Cosmic314

Share this post


Link to post
Share on other sites

didn't look at the code too closely, and from the comments it wasn't really necessary, but....

 

in plain engish, in the strategy pattern, you call a function, and pass it a flag somehow (explicitly or implicitly  - such as "this"), and it in turn calls some sub-function based on that flag.  an example might be some move method that used object type to in turn call a move_ground_target or move_flying_target method.

 

the idea is that you can use one api call move(this) to call different move() methods based on "this", to implement different "flight models".

 

its a common way to generalize and reduce the number of API calls when designing an API.

 

for example, in my game library, i have drawing down to one call: Zdraw(drawinfo) that works for mesh&texture, static model, animated model, 2d billboard, or 3d billboard   (   hey! i should add sprites! <g>   ).   all it does is a switch on drawinfo.type and calls the appropriate sub-function based on type. its a perfect example of the strategy or policy pattern.  drawinfo.type is the strategy or policy to be used when drawing.

Edited by Norman Barrows

Share this post


Link to post
Share on other sites

Is the allocator parameter of C++ standard library containers an example of the strategy pattern? It customizes the logic based off of the allocator passed in, without changing the functionality of the container itself.

Share this post


Link to post
Share on other sites

Is the allocator parameter of C++ standard library containers an example of the strategy pattern? It customizes the logic based off of the allocator passed in, without changing the functionality of the container itself.

Yeah, I think that's about right.

 

In my listen() example, my creature class might implement it as a giant series of if/then/else statements every single time I call listen, even though the state of the creature rarely changes.  Rather than have a giant sequence of if/then/elses I could instead pay that cost one time.  For example when the creature goes deaf I can change the listen() strategy to the deaf strategy, which still happens to use the same interface.  Now I have tidier code.  If I call listen() a zillion times, I save a bundle of branch instructions on that if/then/else tree.  Pardon my poor syntax below, but it's enough to get the idea across (I hope!)

void creature_class::listen()
{
   this->InterfaceListen_strategy->execute();
   // place this creature's specific code afterwards, if any, that is invariant
}

void creature_class::set_listen_strategy( <variables> )
{
  if( DEAF ) this->IntefaceListenStrategy = DeafListenConcrete;
  if( BUFFED ) this->IntefaceListenStrategy = BuffedListenConcrete;
  // etc.
}

Edited by Cosmic314

Share this post


Link to post
Share on other sites
&nbsp;

void creature_class::listen(){&nbsp; &nbsp;this-&gt;InterfaceListen_strategy-&gt;execute();   // place this creature's specific code afterwards, if any, that is invariant}void creature_class::set_listen_strategy( &lt;variables&gt; ){&nbsp; if( DEAF ) this-&gt;IntefaceListenStrategy = DeafListenConcrete;&nbsp; if( BUFFED ) this-&gt;IntefaceListenStrategy = BuffedListenConcrete;&nbsp; // etc.}
Are you sure you want a public set_listen_strategy()? The listening strategy appears to be a very clear cut example of the most private kind of internal state (of class creature_class):

- Nothing "outside" the creature can reasonably have any say in how it listens to noise.
- Changing the strategy at the wrong time might cause errors (e.g. hearing too much or too little), so it should be encapsulated.
- It's a convenience to organize the listening-related code, and the exact same behaviour could be achieved in completely different ways; there's no reason for outside code to depend on such volatile details.
- The events that can cause a change of InterfaceListen_strategy might instead cause a flag to be set, or something else, or no change; the public interface of the creature should match these events (e.g. making the creature hear a deafening noise, already covered by listen() ) rather than exposing a specific way to implement their consequences and constraining creature_class to use it forever because improper dependencies have been established.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!