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();
}
本文详细介绍了策略模式的概念,通过定义一组算法并将其封装起来使它们可以互相替换,从而实现算法独立于使用它的客户端。通过C++代码示例展示了如何将不同行为(如鸭子的叫声)从主体类中分离出来,并通过多态实现灵活的行为切换。
953

被折叠的 条评论
为什么被折叠?



