Article 135 - Design Pattern - Resource Pool Pattern Example

Design patterns were generalized to aid less experienced programmers to learn and adapt theoretical strategies into real world applications. This article goes over a resource pool design pattern example.

It is recommended that the reader review the concepts by reviewing Article 17 - Technical Interview Questions - Design Patterns.

Implementation

Resource pool structure defintion.

typedef struct Resource{
    int content;
    int loaned;
} Resource;

Global variables required throughout the life of the program.

static Resource resources[10];
static int init = 0;

An example to initialize the resource pool. This function is required to be called before resources can be loaned out.

int initResources(){
    int i;

    if( !init ){
        for( i = 0; i < 10; i++ ){
            resources->content = 0;
            resources[i]->loaned = 0
        }

        init = 1;
    }
    else{
        return -1;
    }

    return 0;
}

Retrieve a resource from the pool.

Resource * getResourceFromPool(){
    int i = 0;

    if( !init ){
        return 0;
    }
   
    for( i = 0; i < 10; i++ ){        
        if( !resources[i]->loaned ){
            resources[i]->loaned = 1;
            return resources[i];
        }
    }

    return 0;    
}

Return a resource back to the pool.

int returnResourceToPool( Resource * resource ){
    if( !resource ){
        return -1;
    }

    if( !init ){
        return -2;
    }

    for( i = 0; i < 10; i++ ){        
        if( resources[i] == resource ){
            resource->loaned = 0;
            return 0;
        }
    }

    return -3;
}

Comments (0)

Post a comment

  • Name:
  • Post:
  • Challenge:

Register or login to post comments easier.


Vantasy World Copyright 2011 - 2017. Vantasy World is a project developed by Vantasy Online. Privacy Policy.