Overview
This design pattern solves the problem of having to implement huge switch - case
statements and makes dynamic switch - case
not dependent on the number of cases.
Problem Description
If we have a program used for interpreting and executing commands, as like a Linux shell, and if we assume that we have 300 commands that needs to interpreted and executed, we would need to make a switch - case
statement containing 300 case
s, and what if we have more than 300 commands? Then, we would need more than 300 case
s to handle all those commands. Here, we make a Design Pattern to solve this problem.
Design Pattern Steps
Step 1
Create for every case, only one separate function to handle all the logic of the case.
Collapse
|
Copy Code
void HandleCase1 (int caseNumber)
{
printf(" The Handled Case Number Is = %d",caseNumber);
}
void HandleCase2 (int caseNumber)
{
printf(" The Handled Case Number Is = %d",caseNumber);
}
void HandleCase3 (int caseNumber)
{
printf(" The Handled Case Number Is = %d",caseNumber);
}
Put all of above function into a separate file and name it as HandleCases.cpp.
Step 2
Compile the above file as a shared object (dynamic library) using the following commands:
- g++ -c -fpic HandleCases.cpp
The above command generates an object file HandleCases.o.
- g++ -shared -lc -o HandleCases.so HandleCases.o
Now, we have a dynamic library containing all the case
implementations.
Step 3
Create your main application where we will use this library instead of switch-case
s.
- Define a handle to our dynamic library.
Collapse
|
Copy Code
void* FunctionLib;
- Define a pointer to the called function.
Collapse
|
Copy Code
void (*Function)(int);
- Open the dynamic library using the
dlopen
function.
Collapse
|
Copy Code
FunctionLib = dlopen("dynamic library path", RTLD_LAZY);
- Get the desired function pointer using the
dlsym
function.
Collapse
|
Copy Code
Function =(void(*)(int))dlsym( FunctionLib, "HandleCase1");
- Call this function using the above function pointer.
Collapse
|
Copy Code
(*Function)(1);
- Finally, close the dynamic library.
Collapse
|
Copy Code
dlclose(FunctionLib);
Complete Code of Step 3
Collapse
|
Copy Code
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h> //
int main(int argc,char*argv[])
{
void* FunctionLib;
void (*Function)(int);
char *error;
FunctionLib = dlopen("HandleCases.so",RTLD_LAZY);
if ((error = dlerror()) != NULL)
{
printf ("%s /n", error);
exit(1);
}
Function =(void(*)(int))dlsym( FunctionLib, "HandleCase1");
if ((error = dlerror()) != NULL)
{
printf ("%s/n", error);
exit(1);
}
(*Function)(1);
dlclose(FunctionLib);
return (0);
}