I am copying this example from the other example I posted a day or two ago.
Requirements are very simliliar...
template <class T>
class Method
{
public:
typedef int (T::* MemFunPtr)(char* []);
Method(MemFunPtr pMethod) : mpMethod(pMethod)
{
}
int Invoke(T* pHost, char* pArgs[])
{
return (pHost->*mpMethod())(pArgs);
}
private:
MemFunPtr mpMethod; // has a member function to callback
};
Lets say there are certain ASCI commands and there exist handlers in the
system for those commands These comands are processed in some sort of a
loop. And that, each *type* of command share the handlers. I may choose the
following model
// details are ommitted concept of set of handlers
template <class T>
class Handlers
{
public:
static void AddHandler(const char* pCmdName, Method<T>* pMethod)
{
mHandlers[pCmdName] = pMethod;
}
static void DoHandler(T* pHost, const char* pCmdName, char* pArgs[])
{
MethodType* pMethod = mHandlers.find(pCmdName);
pMethod->Invoke(pHost, pArgs);
}
private :
static map<Method<T>*> mHandlers;
};
// concept of one command with many handlers
class File : Handlers<File>
{
public:
File()
{
AddHandler("open", &open); //do once
}
protected:
int open(char* pArgs[])
{
return (mpFile = fopen(pArgs[0], "r")) ? 0 : -1;
}
private:
FILE* mpFile;
};
class Socket : Handlers<Socket>
{
public:
Socket()
{
AddHandler("open", &open); //do once
}
protected:
int open(char* pArgs[])
{
return (mSocket = socket(AF_INET, ..));
}
private:
int mSocket;
};
// loop can receive commands like "File1" "close", "File2" "open", "Socket3"
// "open" etc etc
void CommandLoop(const char* pCmdName, const char* pSubCmd, char* pArgs[])
{
if (pCmdName == "File1") {
File* pFile = FileCache.find("File1");
if (!pFile)
pFile = new File(); // push to cache as File1
pFile->DoHandler(pFile, pSubCmd, pArgs);
}
if (pCmdName == "Socket1") {
Socket* pSocket = SocketCache.find("Socket1");
if (!pSocket)
pSocket = new Socket(); // push to cache as Socket1
pSocket.DoHandler(pSocket, pSubCmd, pArgs)
}
}