Featured image of post Design Patterns

Design Patterns

Design patterns are the shared language of software design. They capture proven solutions to recurring problems, helping us write code that’s more flexible, maintainable, and easier to reason about.

Strategy Pattern

  • Definition: Strategy pattern defines a family of algorithms, encapsulates each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
using namespace std;

class FlyBehaviorInterface {
public:
    virtual void fly() = 0;
    virtual ~FlyBehaviorInterface() = default;
};

class FlyWithWings : public FlyBehaviorInterface {
public:
    void fly() override {
        cout << "Flying with wings!" << endl;
    }
};

class FlyNoWay : public FlyBehaviorInterface {
public:
    void fly() override {
        cout << "I can't fly!" << endl;
    }
};

class Duck {
public:
    FlyBehaviorInterface* flyBehavior;

    Duck(FlyBehaviorInterface* fb) {
        this->flyBehavior = fb;
    }

    void performFly() {
        flyBehavior->fly();
    }
};

int main() {
    FlyBehaviorInterface* flyWithWings = new FlyWithWings();
    Duck* mallardDuck = new Duck(flyWithWings);
    mallardDuck->performFly(); // Flying with wings!

    FlyBehaviorInterface* flyNoWay = new FlyNoWay();
    Duck* rubberDuck = new Duck(flyNoWay);
    rubberDuck->performFly(); // I can't fly!

    delete flyWithWings;
    delete mallardDuck;
    delete flyNoWay;
    delete rubberDuck;

    return 0;
}

Reference

  1. Okhravi, C. (2016, December 28). Strategy Pattern – Design Patterns (ep 1) [Video]. YouTube. https://www.youtube.com/watch?v=v9ejT8FO-7I
Kernel panic - not syncing: footer overloaded
Built with Hugo
Theme Stack designed by Jimmy