Saturday, October 24, 2009

An example of Interface pattern in use

Interface pattern is a interesting pattern and only recently I realized the value of using it and where people put it into use.

One real interesting use of this that I found was in using callback functions for components.

Say you want to use a component A1 in a class B. But this component A1 needs to get some information from its user, class B, then we need a callback. How does one make sure that the right callback is provided by the implementer. Well interface pattern provides a simple solution for this.

To make to use of interface pattern, we need to implement an abstract class A2. This class should have the function which we want to use as callback as a pure virtual function. Now each class which needs to use component A1, should inherit A2 and implement the desired callback function in A2.

Example, implementation of this is as follows

class A2
{

public:

        void CallBackFunc() = 0;

}

class A1
{

public:

        A2 *user;

         A1(A2 *userClass)
        {

               user = userClass;

        }

        void action()
        {

              user->CallBackFunc();

        }

}

class B : public A2
{

       B()
       {

             A1 *newObj = new A1(this);

       }

        void CallBackFunc()
        {

             //Do something here

              return;

        }

}

1 comment:

dinesh said...

Hi The base class function should be pure virtual function also example is not properly understandable