Design Pattern

Strategy Design Pattern

Strategy is a behavioural design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.

This was introduced super quickly in CS247. Isn’t this just implementing basic Polymorphism?

  • Yup, though there are other ways to implement strategy pattern… StackOverflow

When to use Strategy Pattern?

We want one class to use an algorithm that may be changed at runtime.

Resources

Example

If you need something more advanced, where the the weapon also needs to know what kind of hero you are hitting, look into Visitor Pattern.

class Hero {
	Weapon* w;
	public:
		Hero(Weapon* w): w{w} {}
		void strike() {
			cout << "strike with weapon " << w->getName() << endl;
		}
};
 
class Weapon {
	public:
		virtual string getName() = 0;
}
 
class Sword: public Weapon {
	public:
		virtual string getName() override {
			return "sword";
		}
}
 
class Bow: public Weapon {
	public:
		virtual string getName() override {
			return "bow";
		}
}
 
class Wand: public Weapon {
	public:
		virtual string getName() override {
			return "wand";
		}
}
 
Sword* s;
Hero h{s};
h.strike();