策略模式(附C++代码实现)

当你看到文章标题的时候,一般就知道了什么事策略模式,不过我还是要啰嗦一下,那么,先给出策略模式的定义吧。

定义:

策略模式:软件设计模式的一种,策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。


问题:

一个模拟鸭子的游戏,即有各种各样的鸭子,具有不同的行为,有的鸭子可以飞,有的不可以飞,并且叫声也不同,还有不会叫的鸭子。
如果不知道策略模式的话,那么我们大约有两种比较容易想到的方法来解决这个问题:
1.写一个鸭子的基类,但是这样做的缺点很明显,那就是我们需要每一只鸭子类都必须覆盖基类的函数(方法)。
2.使用接口(C++还没有接口- -!),这样做的缺点就是每一只鸭子类中都要写对应的方法,并且不容易更改。


解决:

于是,这里就用到了策略模式,定义FlyBehavior与QuackBehavior行为接口,并且用这两个接口定义两个变量作为基类的成员变量,而我们创造一组具体的行为类来实现FlyBehavior与QuackBehavior接口,这样,我们就可以让鸭子的某个成员变量(两个接口类型的)来调用每个鸭子对应的方法,这样我们大大减少了代码量,而且使得鸭子改变行为成为了可能(比如本来呱呱叫,突然得病哑了)。

代码较多,知道有些人不喜欢看冗长的文章,于是我决定把代码放到文章最后的链接里,需要的可以去下载,代码不多,命名也比较规范,看起来应该很容易明白。

那接着说策略模式吧,先放一张uml图:
策略模式uml


总结:

设计原则

  1. 代码封装,即相同的代码要独立出来。
  2. 针对接口编程。
  3. 多用组合,少用继承

优缺点:

优点:

  1. 策略模式提供了管理相关的算法族的办法。
  2. 策略模式提供了可以替换继承关系的办法。
  3. 使用策略模式可以避免使用多重条件转移语句。

缺点:

  1. 客户端必须知道所有的策略类。
  2. 策略模式造成很多的策略类。

具体请看百度百科策略模式,感觉总结的优缺点还不错。

最后,给出一段很短的Java代码实现最简单的策略模式(不想看的请无视- -!):

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
//StrategyExample test application
class StrategyExample {
public static void main(String[] args) {
Context context;

// Three contexts following different strategies
context = new Context(new FirstStrategy());
context.execute();

context = new Context(new SecondStrategy());
context.execute();

context = new Context(new ThirdStrategy());
context.execute();
}
}

// The classes that implement a concrete strategy should implement this

// The context class uses this to call the concrete strategy
interface Strategy {
void execute();
}

// Implements the algorithm using the strategy interface
class FirstStrategy implements Strategy {
public void execute() {
System.out.println("Called FirstStrategy.execute()");
}
}

class SecondStrategy implements Strategy {
public void execute() {
System.out.println("Called SecondStrategy.execute()");
}
}

class ThirdStrategy implements Strategy {
public void execute() {
System.out.println("Called ThirdStrategy.execute()");
}
}

// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
Strategy strategy;
// Constructor
public Context(Strategy strategy) {
this.strategy = strategy;
}

public void execute() {
this.strategy.execute();
}
}

下载地址:http://download.csdn.net/detail/u013679882/8579757;

补充:fuck,才发现还需要积分才能下载,csdn是真坑啊,稍候上传到github

欢迎指出不足

显示 Gitment 评论