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

时间:2022-06-15 16:01:49

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

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

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

一、C++代码

 #include <iostream>

 using namespace std;

 //Suppose the position is 1 when strategy is Gnss ,and 2 when strategy is slam
class LocateStrategy{
public:
LocateStrategy(){}
~LocateStrategy(){}
virtual int locateAlgorithm()=;
}; class StrategyGnss:public LocateStrategy
{
public:
StrategyGnss() {}
~StrategyGnss() {}
int locateAlgorithm(){
cout << "Locate By GNSS" << endl;
return ;
}
}; class StrategySlam:public LocateStrategy
{
public:
StrategySlam() {}
~StrategySlam() {}
int locateAlgorithm(){
cout << "Locate By SLAM" << endl;
return ;
}
}; class Context
{
public:
Context(LocateStrategy* strategy) {
_strategy = strategy;
}
~Context(){
delete _strategy;
}
int locateCalculate(){
return this->_strategy->locateAlgorithm();
}
private:
LocateStrategy* _strategy;
}; int main()
{
LocateStrategy *pStrategy = new StrategyGnss();
Context *pCon = new Context(pStrategy);
cout <<pCon->locateCalculate() << endl; //Strategy Replacement
pStrategy = new StrategySlam();
pCon = new Context(pStrategy);
cout <<pCon->locateCalculate() << endl;
}

输出:

Locate By GNSS

Locate By SLAM

二、Java代码

 public interface ILocateStrategy {
int locateAlgorithm();
} public class StrategyGnss implements ILocateStrategy{
public int locateAlgorithm() {
System.out.println("locate calculate by Gnss");
return 1;
}
} public class StrategySlam implements ILocateStrategy {
public int locateAlgorithm() {
System.out.println("locate calculate by Slam");
return 2;
}
} public class Context {
private ILocateStrategy strategy;
public Context(ILocateStrategy strategy){
this.strategy = strategy;
}
public int getPosition(){
return strategy.locateAlgorithm();
}
} public class Main {
public static void main(String[] args){
Context context = new Context(new StrategyGnss());
System.out.println(context.getPosition());
context = new Context(new StrategySlam());
System.out.println(context.getPosition());
}
}

输出:

locate calculate by Gnss
1
locate calculate by Slam
2