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;
}
|