The strategy pattern is to take the parts that vary and encapsulation them, so that later you can alter or extend the parts that vary without affecting those that don't. Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
In the head first design pattern book, the example said that : "fly() and quack() are the parts of the Duck class that vary across ducks". "To separate these behaviours from the Duck class, we will pull both methods out of the Duck class and Create a new set of classes to represent each behaviour. " To make use of this pattern, it is better to first get familiar with polymorphism "dynamic binding"
Sample C++ code:
#include "../header.h"
using namespace std;
class QuackBehavior {
public:
virtual void quack() = 0;
};
class QuackWithSound : public QuackBehavior {
public:
QuackWithSound() {}
~QuackWithSound() {}
void quack() {
cout << "quack with sound" << endl;
}
};
class QuackNoSound : public QuackBehavior {
public:
QuackNoSound() {}
~QuackNoSound() {}
void quack() {
cout << "quack no sound" << endl;
}
};
class Duck{
private:
QuackBehavior* Dquack;
public:
Duck() {}
virtual ~Duck() {}
void swim() {
cout << "a duck can swim" << endl;
}
void setQuackBehavior(QuackBehavior* qBehavior) {
Dquack = qBehavior;
}
void performQuack() {
Dquack->quack();
}
};
class woodenDuck : public Duck{
public:
woodenDuck() {}
~woodenDuck() {}
};
class redDuck : public Duck {
public:
redDuck() {}
~redDuck() {}
};
int main(void) {
QuackBehavior* qBehavior = new QuackWithSound();
Duck* duck = new redDuck();
duck->setQuackBehavior(qBehavior);
duck->performQuack();
}
Maybe better to use "protected" instead of initialize the variable.
#include "../header.h"
using namespace std;
class QuackBehavior {
public:
virtual void quack() = 0;
};
class QuackWithSound : public QuackBehavior {
public:
QuackWithSound() {}
~QuackWithSound() {}
void quack() {
cout << "quack with sound" << endl;
}
};
class QuackNoSound : public QuackBehavior {
public:
QuackNoSound() {}
~QuackNoSound() {}
void quack() {
cout << "quack no sound" << endl;
}
};
class Duck{
protected:
QuackBehavior* Dquack;
public:
Duck() {}
virtual ~Duck() {}
void swim() {
cout << "a duck can swim" << endl;
}
void performQuack() {
Dquack->quack();
}
};
class woodenDuck : public Duck{
public:
woodenDuck() {
Dquack = new QuackNoSound();
}
~woodenDuck() {}
};
class redDuck : public Duck {
public:
redDuck() {
Dquack = new QuackWithSound();
}
~redDuck() {}
};
int main(void) {
Duck* duck = new woodenDuck();
duck->performQuack();
duck = new redDuck();
duck->performQuack();
}