How to call various operations by reusing one API function?

My API function execute_api()must perform certain operations for:

  • method name: view / create / update / delete / update_all / delete_all
  • Method Type: get / post

I want my code to reuse the same logic in execute_api(), but adapt the execution to implement any of the operations listed above. Here is a quick code snippet:

    void execute_api()
    {
        void fill_request_vo( Request& req); // Request is a .oml file
        void calculate_url(Request& req); // calculate the url for the server to hit depending upon the operation selected
        void calculate_header(Request& req); // calculate header for the server to hit depending upon the operation selected

        // execute the services based on some conditions 
        // ResponseVO will be filled in case of success scenerio

        void parse_response(Response& res); // does some logic with the response
     }

Question: In short, I need a better way to reuse this function for any type of method / name listed with just a changing parameter, this is Request.oml.

Below is my solution to this problem, but you need some tips. Please ignore below if you find it long.

My decision:

( enum - view/create/update/delete/update_all/delete_all). , url header.

    switch(req.get_method_name())
    {
    case add:
     // do something - calculate url
     break;
     case view :
     // do something - calculate url
     break;
     .....
     ....

    }

, method_type (get/post)

    switch(req.get_method_type())
    {
    case get:
    // prepare headers accordingly
    break;
    case post:
    // prepare headers accordingly
    break;
    ...
    }

: ? . -

. , - .

+4
1

, Command . http://en.wikipedia.org/wiki/Command_pattern .

, Request (), execute(), .

Request .. , URL-, . , execute_api()

execute_api() {
    ....
    ....
    Response& resp = request.execute(); //Generic for any request type
}

, api . Response.

, .

:

Simple Factory . - Factory

, SimpleRequestFactory, , , .

:

execute_api() {
....
Request& request = SimpleRequestFactory::getInstance()->createRequestObj();  // Singleton SimpleRequestFactory
Response& resp = request.execute(); //Generic for any request type
}

, (), AbstractRequestFactory, , PostRequestFactory, GetRequestFactory .. , execute_api :

execute_api( AbstractRequestFactory& factory ) {
....
Request& request = factory.getRequestObject(/*pass req params*/);
Response& res = request.execute(); //Generic for any request type
}
+6

All Articles