策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数,关系图如下:

十三、策略模式

java版:

package com.shuang.strategy;

public class AbstractCalculator {
	public int[] split(String exp,String opt){
		String array[]=exp.split(opt);
		int arrayInt[]=new int[2];
		arrayInt[0]=Integer.parseInt(array[0]);
		arrayInt[1]=Integer.parseInt(array[1]);
		return arrayInt;
	}
}
package com.shuang.strategy;

public interface ICalculator {
	public int calculate(String exp);
}
package com.shuang.strategy;

public class Minus extends AbstractCalculator implements ICalculator{

	@Override
	public int calculate(String exp) {
		int arrayInt[]=split(exp, "-");
		return arrayInt[0]-arrayInt[1];
	}

}
package com.shuang.strategy;

public class Plus extends AbstractCalculator implements ICalculator{

	@Override
	public int calculate(String exp) {
		int arrayInt[]=split(exp, "\\+");
		return arrayInt[0]+arrayInt[1];
	}

}
package com.shuang.strategy;

public class StrategyTest {
	public static void main(String[] args) {
		String exp="2+8";
		ICalculator calculator=new Plus();
		int result=calculator.calculate(exp);
		System.out.println(result);
	}
}

c++版:

#include<iostream>
using namespace std;
class Strategy
{
public:
	virtual void crypt()=0;
};
class AES:public Strategy
{
public:
	virtual void crypt()
	{
		cout<<"AES加密算法"<<endl;
	}
};
class DES:public Strategy
{
public:
	virtual void crypt()
	{
		cout<<"DES加密算法"<<endl;
	}
};
class Context
{
public:
	void setStragegy(Strategy *strategy)
	{
		this->strategy=strategy;
	}
	void myoperator()
	{
		strategy->crypt();
	}
private:
	Strategy *strategy;
};
int main()
{
	Strategy *strategy=NULL;
	strategy=new DES;
	Context *context=new Context;
	context->setStragegy(strategy);
	context->myoperator();
	delete strategy;
	delete context;
	system("pause");
	return 0;
}

 

相关文章:

  • 2021-05-29
  • 2021-08-06
  • 2022-12-23
  • 2022-12-23
  • 2021-06-30
  • 2018-07-23
  • 2021-09-26
猜你喜欢
  • 2021-04-12
  • 2021-07-23
  • 2021-11-29
  • 2021-10-27
  • 2021-09-03
  • 2021-10-19
  • 2021-06-09
相关资源
相似解决方案