forked from mechusatveer/Design-Patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDelegation.cpp
More file actions
104 lines (89 loc) · 1.71 KB
/
Copy pathDelegation.cpp
File metadata and controls
104 lines (89 loc) · 1.71 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
Delegation makes composition as powerful for reuse as inheritance.
With delegation, two objects are involved in handling a request.
A receiving object delegates operations to its delegate, which is
similar to the case when subclass defers requests to parent class.
#include <iostream>
using namespace std;
class Rectangle
{
private:
double height, width;
public:
Rectangle(double h, double w) {
height = h;
width = w;
}
double area() {
cout << "Area of Rect. Window = ";
return height*width;
}
};
class Window
{
public:
Window(Rectangle *r) : rectangle(r){}
double area() {
return rectangle->area();
}
private:
Rectangle *rectangle;
};
int main()
{
Window *wRect = new Window(new Rectangle(10,20));
cout << wRect->area();
return 0;
}
The main advantage of delegation is that it makes it easy to compose behaviors
at run-time. For example, the Window can become circular at run-time as shown
in the following code.
#include <iostream>
using namespace std;
class Shape
{
public:
virtual double area() = 0;
};
class Rectangle : public Shape
{
private:
double height, width;
public:
Rectangle(double h, double w) {
height = h;
width = w;
}
double area() {
return height*width;
}
};
class Circle : public Shape
{
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double area() {
return 3.14*radius*radius;
}
};
class Window
{
public:
Window (Shape *s):shape(s){}
double area() {
return shape->area();
}
private:
Shape *shape;
};
int main()
{
Window *wRect = new Window(new Rectangle(10,20));
Window *wCirc = new Window(new Circle(20));
cout << "rectangular Window:" << wRect->area() << endl;
cout << "circular Window:" << wCirc->area() << endl;
return 0;
}