假设我有一个策略模式,其中有两个类实现策略,其中每个类都有一些值,但值存储在不同的容器中,比如矢量和列表。
我想有一个迭代器,允许我查看每个类中的每个值。 我还希望能够使用标准迭代器方式,这意味着以这种方式遍历值:
Strategy s = //Some initialization.
Strategy :: iterator it;
for (it = s.begin(); it != s.end() ; ++it){
//Do something with *it.
}
现在我唯一的解决方案是:策略类具有上下文迭代器的另一种策略模式。另一个策略导师和每个“策略实施类”都有自己的类自我导师:公共策略导师。
但这似乎很麻烦,也许别人比我有更多的创造力。 所以我真的很感激一些想法:),谢谢!
这是一个操作多项式的程序,其中策略是多项式的表示,一个带有向量,另一个带有列表。
这里也是我想用它的程序的H文件:
#include <iostream>
#include <vector>
#include <list>
using namespace std;
#ifndef MYPOLY_H
#define MYPOLY_H
class PolyRep;
class RegIterator;
typedef enum Poly
{
REG_POLY = 1, SPARSE_POLY = 2
};
/* =============================================================================
* MyPoly class.
* =============================================================================*/
class MyPoly
{
public:
MyPoly(double arr[], unsigned int arrSize);
MyPoly(double num);
MyPoly(double X[], double Y[], int arrSize);
MyPoly(string sPoly);
~MyPoly();
string toString();
double evaluate(double x) const;
MyPoly derive(int n);
MyPoly & operator =(const MyPoly &rhs);
MyPoly & operator +=(const MyPoly &rhs);
MyPoly & operator -=(const MyPoly &rhs);
MyPoly & operator *=(const MyPoly &rhs);
MyPoly operator +(const MyPoly& other);
MyPoly operator -(const MyPoly& other);
MyPoly operator *(const MyPoly& other);
bool operator ==(const MyPoly& b) const;
MyPoly operator -() const;
private:
PolyRep * _poly;
};
/* =============================================================================
* PolyRep class.
* =============================================================================*/
class PolyRep
{
public:
virtual double evaluate(const double &x) const = 0;
//virtual iterator begin () = 0;
//virtual PolyRep * derive(int n) = 0;
protected:
int _degree;
};
/* =============================================================================
* RegPoly class.
* =============================================================================*/
class RegPoly : public PolyRep
{
public:
RegPoly(double arr[], int degree);
~RegPoly();
double evaluate(const double &x) const;
private:
vector <double> _values;
};
/* =============================================================================
* SparsePoly class.
* =============================================================================*/
class SparsePoly : public PolyRep
{
public:
SparsePoly(double arr[], int degree);
~SparsePoly();
double evaluate(const double &x) const;
private:
/*A class to represent a node in the SaprsePoly list.*/
class SparseNode
{
public:
SparseNode(int n = 0, double value = 0);
int getN() const;
double getValue() const;
private:
int _n;
double _value;
};
/*End of sparse node class.*/
list <SparseNode*> _values;
};
#endif /* MYPOLY_H */