您的位置:首页 > 其它

设计模式之行为模式-命令,迭代器,中介者,观察者,模板方法

2014-03-31 18:05 645 查看
目录[-]

1 命令模式

2 迭代器模式

3 中介者模式

4 观察者模式

5 模板方法模式


1 命令模式

对每个执行请求进行封装。

01
interface
Command {
02
void
execute();
03
};
04
class
OpenCommand
: Command {
05
void
execute()
{
06
//
open file
07
}
08
}
09
class
CloseCommand
: Command {
10
void
execute()
{
11
//
close file
12
}
13
}
14
//
菜单项实体与执行过程的解耦
15
class
MenuItem
{
16
string
m_caption;
17
Command
m_command;
18
 
19
void
on_clicked()
{
20
m_command.execute();
21
}
22
};
23
//
复合命令
24
class
CompositeCommand
: Command {
25
OpenCommand
m_openCmd;
26
CloseCommand
m_closeCmd;
27
 
28
void
execute()
{
29
m_openCmd.execute();
30
//
write file ...
31
m_closeCmd.execute();
32
}
33
}


2 迭代器模式

顺序访问容器对象中的各个元素,同时不暴露容器的内部实现。

1
std::list<
int
>
lst;
2
std::list<
int
>::iterator
iter = lst.begin();
3
while
(
iter != lst.end() ) {
4
printf
(
"%d\n"
,
*iter);
5
++iter;
6
}


3 中介者模式

用一个中介对象,封装其他一系列对象的交互操作,减少这些其他对象间操作的耦合依赖。

示例:

1. 按钮点击后,在文本框中显示消息。

2. 按钮与文本框没有直接耦合依赖,按钮通过中介窗口传递消息。

01
//
中介接口
02
interface
Mediator {
03
void
button_clicked();
04
}
05
class
Button
{
06
Mediator
m_mediator;
07
08
//
按钮的点击事件,通知中介者进行处理
09
void
on_click()
{
10
m_mediator.button_clicked();
11
}
12
}
13
class
TextBox
{
14
void
setText(string
text) { ... }
15
}
16
class
Window
: Mediator {
17
Button
m_button;
18
TextBox
m_textbox;
19
 
20
void
init()
{
21
m_button.m_mediator
=
this
;
22
}
23
//
按钮通过窗口将事件消息传递给
24
void
button_clicked()
{
25
m_textbox.setText(
"button
clicked"
);
26
}
27
}


4 观察者模式

对象间的一对多依赖关系,一个对象状态发生改变,其他依赖其的对象会立即得到通知。

另称为订阅-发布模式。

01
class
Observer
{
02
void
update(
int
state);
03
}
04
 
05
class
Subject
{
06
vector<Observer>
m_obsList;
07
int
m_state;
08
 
09
void
addObserver(Observer
obs) {
10
m_obsList.add(obs);
11
}
12
 
13
void
changeState(
int
state)
{
14
m_state
= state;
15
for
(i
= 0; i < m_obsList.size(); ++i) {
16
m_obsList[i].update(state);
17
}
18
}
19
}


5 模板方法模式

定义一个固定的算法或执行过程骨架,执行或算法的详细过程在子类中实现。

view
source

print?

01
class
Storage
{
02
public
:
03
//
对外公共接口,实现用于向目标存储单元写入数据的骨架过程
04
void
saveData(
char
[]
data) {
05
this
.open();
06
this
.write(data);
07
this
.close();
08
}
09
protected
:
10
//
由具体的存储单位实现
11
void
open()
{}
12
void
write(
char
[]
data) {}
13
void
close()
{}
14
}
15
 
16
//
文件存储单元
17
class
FileStorage
: Storage {
18
void
open()
{
19
//
open file ...
20
}
21
void
write(
char
[]
data) {
22
//
write data to file
23
}
24
void
close()
{
25
//
close file
26
}
27
}
28
 
29
//
数据库存储单元
30
class
DBStorage
: Storage {
31
void
open()
{
32
//
open db connection ...
33
}
34
void
write(
char
[]
data) {
35
//
insert data to db table
36
}
37
void
close()
{
38
//
close db connection
39
}
40
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐