跳转至

策略模式

时间:2017-12-02 23:25:29

参考:

  1. 设计模式之禅 [秦小波]

#

策略模式(Strategy Pattern)#

把多个策略抽象出来,由具体的调用者决定在调用的时候使用什么策略。

Deifine a family of algorithms, encapsulate each one, and make them interchangeable.

定义一组算法,封装每一个算法,是他们可以互换。

类图#

策略模式

简单策略代码#

 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
//策略接口  
class interface Strategy {
    public void exec();
}

//策略A
class StrategyA implements Strategy {

    public void exec() {
        System.out.println("A");
    }
}
//策略B
class StrategyB implements Strategy {

    public void exec() {
        System.out.println("A");
    }
}

//容器类,持有策略
class Context {
    private Strategy strategy;

    public Context(Strategy startegy) {
        this.strategy = strategy;
    }
    public void run() {
        strategy.exec();
    }
}

// 客户端调用
class Client {
    public static void main(String[] args) {    
        new Context(new StrategyA().exec());
        new Context(new StrategyB().exec());
    }
}

工厂模式加策略模式#

策略模式