两种语言实现设计模式(C++和Java)(三:策略模式)

策略模式是指定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。也就是说这些算法所完成的功能一样,对外的接口一样,只是各自实现上存在差异。用策略模式来封装算法,效果比较好。

本文以自己实际项目中策略模式的实际应用为例:实现无人驾驶车辆的定位有两种方式:GNSS(带差分信号的GPS)和SLAM,实现两种方法的定位可以视为采用两种不同的策略。定义抽象类locateStratey,再通过委托的方式将具体的算法实现委托给具体的Strategy类来实现。

Context委托类是Strategy模式的关键,*Strategy通过“组合”(委托)方式实现算法(实现)的异构,

一、C++代码

 

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 //Suppose the position is 1 when strategy is Gnss ,and 2 when strategy is slam
 6 class LocateStrategy{
 7 public:
 8     LocateStrategy(){}
 9     ~LocateStrategy(){}
10     virtual int locateAlgorithm()=0;
11 };
12 
13 class StrategyGnss:public LocateStrategy
14 {
15 public:
16     StrategyGnss() {}
17     ~StrategyGnss() {}
18     int locateAlgorithm(){
19         cout << "Locate By GNSS" << endl;
20         return 1;
21     }
22 };
23 
24 class StrategySlam:public LocateStrategy
25 {
26 public:
27     StrategySlam() {}
28     ~StrategySlam() {}
29     int locateAlgorithm(){
30         cout << "Locate By SLAM" << endl;
31         return 2;
32     }
33 };
34 
35 class Context
36 {
37 public:
38     Context(LocateStrategy* strategy) {
39         _strategy = strategy;
40     }
41     ~Context(){
42         delete _strategy;
43     }
44     int locateCalculate(){
45        return this->_strategy->locateAlgorithm();
46     }
47 private:
48     LocateStrategy* _strategy;
49 };
50 
51 int main()
52 {
53     LocateStrategy *pStrategy = new StrategyGnss();
54     Context *pCon = new Context(pStrategy);
55     cout <<pCon->locateCalculate() << endl;
56 
57     //Strategy Replacement
58     pStrategy = new StrategySlam();
59     pCon = new Context(pStrategy);
60     cout <<pCon->locateCalculate() << endl;
61 }

 

输出:

Locate By GNSS

1

Locate By SLAM

2

二、Java代码

 

 1 public interface ILocateStrategy {
 2     int locateAlgorithm();
 3 }
 4 
 5 public class StrategyGnss implements ILocateStrategy{
 6     public int locateAlgorithm() {
 7         System.out.println("locate calculate by Gnss");
 8         return 1;
 9     }
10 }
11 
12 public class StrategySlam implements ILocateStrategy {
13     public int locateAlgorithm() {
14         System.out.println("locate calculate by Slam");
15         return 2;
16     }
17 }
18 
19 public class Context {
20     private ILocateStrategy strategy;
21     public Context(ILocateStrategy strategy){
22         this.strategy = strategy;
23     }
24     public int getPosition(){
25         return  strategy.locateAlgorithm();
26     }
27 }
28 
29 public class Main {
30     public static void main(String[] args){
31         Context context = new Context(new StrategyGnss());
32         System.out.println(context.getPosition());
33         context = new Context(new StrategySlam());
34         System.out.println(context.getPosition());
35     }
36 }

输出:

locate calculate by Gnss
1
locate calculate by Slam
2

 

posted @ 2019-04-24 20:40  Asp1rant  阅读(243)  评论(0编辑  收藏  举报