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()
以上只是个人对策略模式的理解,分别使用静态语言与动态语言实现,仅供参考,如有问题欢迎指正