-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompositePattern.cpp
More file actions
74 lines (65 loc) · 1.47 KB
/
compositePattern.cpp
File metadata and controls
74 lines (65 loc) · 1.47 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
// compositePattern.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<vector>
// abstract base class for Graphics component
class Graphic{
public :
virtual void print() = 0;
};
// composite class for groups of graphical shapes / individual shapes / groups of groups
class Composite: public Graphic
{
public:
std::vector<Graphic *> shapeList; // list of shapes is stored in this vector
void add(Graphic *g){
shapeList.push_back(g);
}
void print(){
for ( std::vector<Graphic *>::iterator itr = shapeList.begin(); itr != shapeList.end(); itr++)
(*itr)->print();
}
};
class square : public Graphic{
int sideLength;
public:
square(int x = 4){
sideLength = x;
}
void print(){
std::cout<<"\n A square of side = "<< sideLength;
}
};
class rectangle: public Graphic{
int len;
int wid;
public:
rectangle(int l=3, int b=2){
len = l;
wid = b;
}
void print(){
std::cout<<"n a rectangle of len= "<<len<< "breadth = "<<wid;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
// creating 2 squares 1 rectangle
square *s1 = new square(7);
square *s2 = new square(8);
rectangle *r1 = new rectangle(3,4);
// creating 2 composites c1
Composite *c1 = new Composite();
Composite *c2 = new Composite();
// c1 has a square and rectangle
c1->add(s1);
c1->add(r1);
// c2 has only 1 square
c2->add(s2);
// invoke print() on a composite or a single object
r1->print();
c1->print();
c2->print();
return 0;
}