在此模式中,算法是从复杂类提取的,因而可以方便地替换。例如,如果要更改搜索引擎中排列页的方法,则策略模式是一个不错的选择。思考一下搜索引擎的几个部分 —— 一部分遍历页面,一部分对每页排列,另一部分基于排列的结果排序。在复杂的示例中,这些部分都在同一个类中。通过使用策略模式,您可将排列部分放入另一个类中,以便更改页排列的方式,而不影响搜索引擎的其余代码。
作为一个较简单的示例,清单显示了一个用户列表类,它提供了一个根据一组即插即用的策略查找一组用户的方法。
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
|
<?php
//策略接口
interface
IStrategy
{
function
filter(
$record
);
}
//定义一种策略继承接口
class
FindAfterStrategy
implements
IStrategy
{
private
$_name
;
public
function
__construct(
$name
)
{
$this
->_name =
$name
;
}
public
function
filter(
$record
)
{
return
strcmp
(
$this
->_name,
$record
) <= 0;
}
}
//定义另一种策略
class
RandomStrategy
implements
IStrategy
{
public
function
filter(
$record
)
{
return
rand( 0, 1 ) >= 0.5;
}
}
//定义用户列表类
class
UserList
{
private
$_list
=
array
();
public
function
__construct(
$names
)
{
if
(
$names
!= null )
{
foreach
(
$names
as
$name
)
{
$this
->_list []=
$name
;
}
}
}
public
function
add(
$name
)
{
$this
->_list []=
$name
;
}
//根据某个策略来获取用户
public
function
find(
$filter
)
{
$recs
=
array
();
foreach
(
$this
->_list
as
$user
)
{
if
(
$filter
->filter(
$user
) )
$recs
[]=
$user
;
}
return
$recs
;
}
}
//初始化用户列表
$ul
=
new
UserList(
array
(
"Andy"
,
"Jack"
,
"Lori"
,
"Megan"
) );
//根据第一个策略获取用户
$f1
=
$ul
->find(
new
FindAfterStrategy(
"J"
) );
echo
'<pre>'
;
print_r(
$f1
);
echo
'</pre>'
;
//根据第二个策略获取用户
$f2
=
$ul
->find(
new
RandomStrategy() );
echo
'<pre>'
;
print_r(
$f2
);
echo
'</pre>'
;
|
UserList
类是打包名称数组的一个包装器。它实现 find
方法,该方法利用几个策略之一来选择这些名称的子集。这些策略由 IStrategy
接口定义,该接口有两个实现:一个随机选择用户,另一个根据指定名称选择其后的所有名称。运行测试代码时,将得到以下输出:
测试代码为两个策略运行同一用户列表,并显示结果。在第一种情况中,策略查找排列在 J
后的任何名称,所以您将得到 Jack、Lori 和 Megan。第二个策略随机选取名称,每次会产生不同的结果。在这种情况下,结果为 Andy 和 Megan。
策略模式非常适合复杂数据管理系统或数据处理系统,二者在数据筛选、搜索或处理的方式方面需要较高的灵活性。
本文转自shayang8851CTO博客,原文链接:http://blog.51cto.com/janephp/1344201,如需转载请自行联系原作者