Re: design pattern for defining a relational operator
"newbie" <mitbbsmj@yahoo.com> wrote in message
news:1180992714.345351.189170@x35g2000prf.googlegroups.com...
I want the DataAnDRelation is flexible in design so that client code
can define its own relationship according to their own needs.
I am trying to use function pointer, but that needs client code to
declare friendship in the class DataAndRelation, which I feel not
neat. Any design pattern/standard way to solve this problem.
bool MyRelation(double a, double b) {
return a > b;
}
bool MyRelationABS(double a, double b) {
return abs(a) > abs(b);
}
class DataAndRelation {
public:
DataAndRelation (double a, bool (*ptr )(double, double) ) { data =
a; ptr_relation = ptr; }
~DataAndRelation () {}
bool GreatOrEaqual (const DataAndRelation& other) const {
return (*ptr_relation) (this->data, other.data);
}
private:
double data;
bool (*ptr_relation )(double, double);
}
int main() {
DataAndRelation example(1.0, MyRelation);
DataAndRelation example2(2.0, MyRelationABS);
...
...
}
What about something like this? Basically I've replaced function pointers
with real objects or functors.
This is based upon some pattern, "strategy" perhaps ?
dave
#include "math.h"
class Relation
{
public:
virtual bool compare( double a, double b) const = 0;
virtual ~Relation();
};
class LessThan : public Relation
{
public:
virtual bool compare( double a, double b) const
{
return a < b;
}
};
class LessAbs : public Relation
{
public:
virtual bool compare( double a, double b) const
{
return fabs(a) < fabs(b);
}
};
class DataAndRelation
{
public:
DataAndRelation (double a, Relation* relation )
:_data(a), _relation(relation)
{
}
bool GreatOrEaqual (const DataAndRelation& other) const
{
return _relation->compare( _data, other.data() );
}
double data() const { return _data ;}
private:
double _data;
Relation* _relation;
};
int main()
{
LessThan lessThan;
LessAbs lessAbs;
DataAndRelation example(1.0, &lessThan);
DataAndRelation example2(2.0, &lessAbs);
return 0;
}