1
#pragma once
2
3
class component
4
{
5
public
:
6
component(void);
7
virtual void printsefl()
=
0
;
8
public
:
9
virtual ~component(void);
10
};
11
12
class concreatecom :
public
component
13
{
14
public
:
15
concreatecom(char
*
);
16
virtual void printsefl() ;
17
virtual ~concreatecom(void);
18
protected:
19
private
:
20
char
*
_psz_text;
21
};
22
23
class decorator:
public
component
24
{
25
public
:
26
decorator(component
&
);
27
virtual void printsefl() ;
28
virtual ~decorator();
29
protected:
30
31
private
:
32
component
&
_pcomponent;
33
};
34
class headdeco:
public
decorator
35
{
36
public
:
37
headdeco(component
&
,
int
);
38
virtual void printsefl() ;
39
virtual ~headdeco();
40
protected:
41
virtual void printhead() ;
42
private
:
43
int
_i_head;
44
};
45
46
class enddeco:
public
decorator
47
{
48
public
:
49
enddeco(component
&
,char
*
);
50
virtual void printsefl() ;
51
virtual ~enddeco();
52
protected:
53
virtual void printend() ;
54
private
:
55
char
*
_pch_end;
56
};
1
#include
"
StdAfx.h
"
2
#include
<
iostream
>
3
#include
"
component.h
"
4
using namespace std;
5
6
component::component(void)
7
{
8
}
9
10
component::~component(void)
11
{
12
}
13
14
void concreatecom::printsefl()
15
{
16
cout
<<
endl;
17
cout
<<
_psz_text ;
18
cout
<<
endl;
19
}
20
concreatecom::concreatecom(char
*
psz)
21
{
22
_psz_text
=
psz;
23
}
24
decorator::decorator(component
&
a):
25
_pcomponent(a)
26
{
27
28
}
29
concreatecom::~concreatecom()
30
{
31
32
}
33
void decorator::printsefl()
34
{
35
_pcomponent.printsefl();
36
37
}
38
39
decorator::~decorator()
40
{
41
42
}
43
44
headdeco::headdeco(component
&
refcom,
int
i):
45
decorator(refcom)
46
,_i_head(i)
47
{
48
49
}
50
void headdeco::printsefl()
51
{
52
printhead();
53
decorator::printsefl();
54
55
}
56
void headdeco::printhead()
57
{
58
cout
<<
endl;
59
cout
<<
_i_head;
60
cout
<<
endl;
61
}
62
headdeco::~headdeco()
63
{
64
65
}
66
67
enddeco::enddeco(component
&
refcom,char
*
pch)
68
:decorator(refcom)
69
,_pch_end(pch)
70
{
71
72
}
73
void enddeco::printsefl()
74
{
75
decorator::printsefl();
76
printend();
77
}
78
void enddeco::printend()
79
{
80
cout
<<
endl;
81
cout
<<
_pch_end;
82
cout
<<
endl;
83
}
84
enddeco::~enddeco()
85
{
86
87
}
1
//
decorator.cpp : 定义控制台应用程序的入口点。
2
//
3
4
#include
"
stdafx.h
"
5
#include
<
iostream
>
6
#include
"
component.h
"
7
using namespace std;
8
9
void printmodel(component
&
pcom )
10
{
11
pcom.printsefl();
12
}
13
int
_tmain(
int
argc, _TCHAR
*
argv[])
14
{
15
16
printmodel(headdeco(headdeco(enddeco(concreatecom(
"
正文输出中。。。。
"
),
"
黄大仙
"
),
2
),
1
));
17
return
0
;
18
}
19
这个decorator 模式例子让初学者 更能加深 多态威力的体会和 decorator 模式 比子类灵活的体会
要注意的问题是:对象链总是在 concreatecomponent 对象处结束。
///此处是client 使用 对象的入口点,仅仅得到了 1个 decorator 的派生类对象,client 什么都不知道
printmodel(headdeco(headdeco(enddeco(concreatecom("正文输出中。。。。"),"黄大仙"),2),1));
///
在vc2005 下通过
posted on 2007-03-22 09:56
黄大仙 阅读(2089)
评论(1) 编辑 收藏 引用 所属分类:
c++