Thursday, December 23, 2010

Strategy pattern implementation using member function pointer.

Strategy pattern is used when there are various ways to solve one problem. Normally each algorithm to solve problem is implemented as a class. And those classes are inherited from base class. However, it's also possible to implement those pattern using member function pointers though it looks a bit quirky like (instace.*instance.functionPointer)(...). :)


#include <iostream>

class Class {
public:
  typedef enum OPERATION {
    SUM = 0,
    MUL
  } operation;

  Class();

  int func(int a, int b, operation op);
  int (Class::*fp[2])(int a, int b);
private:

  int sum(int a, int b);
  int mul(int a, int b);
};

Class::Class()
{
  fp[SUM] = &Class::sum;
  fp[MUL] = &Class::mul;
}

int
Class::func(int a, int b, Class::operation op)
{
  return (this->*fp[op])(a, b);
}

int
Class::sum(int a, int b)
{
  return a + b;
}

int
Class::mul(int a, int b)
{
  return a * b;
}

int main()
{
  Class c;

  std::cout << c.func(2, 4, Class::SUM) << std::endl;
  std::cout << (c.*c.fp[Class::MUL])(2, 4) << std::endl;
  return 0;
}

No comments:

Post a Comment