Strategy

C++ Code:

#include <iostream>

class AlgorithmInterface
{
public:
	virtual int CalAns(int lhs, int rhs) = 0;
};

class SubMethod : public AlgorithmInterface
{
public:
	virtual int CalAns(int lhs, int rhs) { return lhs - rhs; }
};

class PlusMethod : public AlgorithmInterface
{
public:
	virtual int CalAns(int lhs, int rhs) { return lhs + rhs; }
};

class MulMethod : public AlgorithmInterface
{
public:
	virtual int CalAns(int lhs, int rhs) { return lhs * rhs; }
};

class Strategy
{
private:
	char _algType;

public:
	Strategy(char t) : _algType( t ) {}
	AlgorithmInterface* GetAlgorithmInterfacePtr(void);
};

AlgorithmInterface* Strategy::GetAlgorithmInterfacePtr(void)
{
	//default is MulMethod
	if( '-' == _algType )
		return new SubMethod();
	else if( '+' == _algType )
		return new PlusMethod();
	else if( '*' == _algType )
		return new MulMethod();
	return NULL;
}

class Context
{
private:
	int 		_lhs;
	int 		_rhs;
	Strategy*	_strategy;

public:
	Context(int lhs, int rhs, char algType) : \
	_lhs(lhs), _rhs(rhs) { _strategy = new Strategy(algType); }
	~Context(void) { delete _strategy; }

	int GetAns(void) 
	{ 
		AlgorithmInterface* ptr = _strategy->GetAlgorithmInterfacePtr();
		if( NULL == ptr )
			return -1;
		return ptr->CalAns(_lhs, _rhs);
	}
};

int main(int argc, char const *argv[])
{
	int lhs 		= 10201;
	int rhs 		= 20102;

	Context dat(lhs, rhs, '+');
	std::cout << dat.GetAns() << std::endl;

	Context dat1(lhs, rhs, '*');
	std::cout << dat1.GetAns() << std::endl;


	Context dat2(lhs, rhs, '/');
	std::cout << dat2.GetAns() << std::endl;

	return 0;
}
Python Code:
class PlusMethod(object):
	def CalAns(self, lhs, rhs):
		return lhs + rhs
	
class SubMethod(object):
	def CalAns(self, lhs, rhs):
		return lhs - rhs
	
class MulMethod(object):
	def CalAns(self, lhs, rhs):
		return lhs * rhs
	
class Strategy(object):
	def __init__(self, algType):
		self._algType = algType
	
	def GetMethodRef(self):
		if '+' == self._algType:
			return PlusMethod()
		elif '-' == self._algType:
			return SubMethod()
		elif '*' == self._algType:
			return MulMethod()
		else:
			return None
		
class Context(object):
	def __init__(self, lhs, rhs, algType):
		self._lhs		= lhs
		self._rhs		= rhs
		self._strategy 	= Strategy(algType)
		
	def CalAns(self):
		methodRef = self._strategy.GetMethodRef()
		if not methodRef:
			return -1
		return methodRef.CalAns(self._lhs, self._rhs)
	
if "__main__" == __name__:
	lhs = 10201
	rhs = 20102
	
	print Context(lhs, rhs, '+').CalAns()
	print Context(lhs, rhs, '*').CalAns()
	print Context(lhs, rhs, '/').CalAns()
	
	
	
以上只是个人对策略模式的理解,分别使用静态语言与动态语言实现,仅供参考,如有问题欢迎指正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值