-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomposit.cpp
128 lines (106 loc) · 1.85 KB
/
composit.cpp
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <string>
#include <list>
using namespace std;
class IComponent
{
public:
explicit IComponent( const string& name )
:m_name( name )
{
}
virtual void add( IComponent* comp )
{
cout<<"can't add"<<endl;
}
virtual void del( IComponent* comp )
{
cout<<"can't delete"<<endl;
}
const string& getName( ) const
{
return m_name;
}
virtual ~IComponent( )
{
}
virtual void display( int depth ) const = 0;
protected:
void printDepth( int depth ) const
{
while( depth )
{
depth--;
cout<<"---";
}
}
private:
string m_name;
};
class Leaf : public IComponent
{
public:
explicit Leaf( const string& name )
: IComponent( name )
{
}
void display( int depth ) const
{
const string& name = getName( );
printDepth( depth );
cout<<"---leaf "<<name<<endl;
}
};
class Composit : public IComponent
{
public:
explicit Composit( const string& name )
: IComponent( name )
{
}
void add( IComponent* comp )
{
m_lists.push_back( comp );
m_lists.unique( );
}
void del( IComponent* comp )
{
list<IComponent*>::iterator iter = m_lists.begin( );
for( ;iter != m_lists.end( ); iter++ )
{
if( *iter == comp )
{
m_lists.erase( iter );
break;
}
}
}
void display( int depth = 0 ) const
{
printDepth( depth );
depth++;
cout<<"---composit "<<getName( )<<endl;
list<IComponent*>::const_iterator iter = m_lists.begin( );
for( ;iter != m_lists.end( ); iter++ )
{
const IComponent* comp = *iter;
comp->display( depth );
}
}
private:
list<IComponent*> m_lists;
};
int main( )
{
Leaf lf1( string( "lf1" ) );
Leaf lf2( string( "lf2" ) );
Composit comp1( string( "comp1" ) );
comp1.add( &lf1 );
comp1.add( &lf2 );
Composit comp2( string( "comp2" ) );
comp2.add( &comp1 );
Leaf lf3( string( "lf3" ) );
comp2.add( &lf3 );
comp2.display( );
return 0;
}