Definition
The strategy pattern defines a families of algorithms and lets the clients choose from it and can change independently.
Scenario
Inheritance is not for code reuse. Inheritance shares code downward, but not horizontally. Using composition rather than inheritance. This is like passing in a function pointer, but this uses interface to gaurantee a specific implementation.
Class Diagram
This singles out behaviors or algorithms and lets the client to choose from, so that they can combine and have multiple options if there are more than one behavior. Here, it only has one Quack()
.
Used Cases
- When we want to create objects that can have different behaviors to choose from.
- Example: There are algorithm A, B, C …, and we want to pick one of them based on specific cases.
Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// duck.h
#ifndef __DUCK_H__
#define __DUCK_H__
#include <iostream>
#include <memory>
class IQuackBehavior {
public:
virtual void Quack() = 0;
};
class SimpleQuackBehavior : public IQuackBehavior {
public:
void Quack() override;
};
class NoQuackBehavior : public IQuackBehavior {
public:
void Quack() override;
};
class Duck {
public:
Duck(std::unique_ptr<IQuackBehavior>&& quack_behavior);
void Quack();
void SetQuack(std::unique_ptr<IQuackBehavior>&& quack_behavior);
private:
std::unique_ptr<IQuackBehavior> quack_behavior_;
};
#endif //__DUCK_H__
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// duck.cpp
#include "duck.h"
#include <iostream>
void SimpleQuackBehavior::Quack() { std::cout << "Simple Quack ... " << std::endl; }
void NoQuackBehavior::Quack() { std::cout << "No Quack ... " << std::endl; }
Duck::Duck(std::unique_ptr<IQuackBehavior>&& quack_behavior) {
quack_behavior_ = std::move(quack_behavior);
}
void Duck::SetQuack(std::unique_ptr<IQuackBehavior>&& quack_behavior) {
quack_behavior_ = std::move(quack_behavior);
}
void Duck::Quack() { quack_behavior_->Quack(); }
1
2
3
4
5
6
7
8
9
10
// main.cpp
#include "duck.h"
int main() {
Duck something_duck = Duck(std::make_unique<SimpleQuackBehavior>());
something_duck.Quack();
something_duck.SetQuack(std::make_unique<NoQuackBehavior>());
something_duck.Quack();
return 0;
}