Article 137 - Design Pattern - Adapter 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 an adapter design pattern example.

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

Implementation

In this implementation, we use the Node structure from the Link List Article, see Article 83 - Data Structure - How to Implement Linked List in C.

A function that performs some functionality, in this case producing the sum, over the input.

int sum( Node * list ){
    int sum;

    for( ; list; list = list->next ){
        sum += list->content;
    }
}

Another function that performs some functionality, in this case finding the maximum, over the input. This function has a different input parameter type.

int max( int * list, unsigned int count ){
    int max = 0x80000000; 
    //assuming int is 4 bytes in size represented in two's complement

    for( ; count > 0; count-- ){
        if( *list > max ){
            max = *list;
        }

        list++;
    }
}

An adapter function that bridges the two functions. It converts the type to the compatible type.

int maxAdapter( Node * list ){
    int size = 0;
    int i;
    int * intList;
    int Node * listPointer;
    int max;

    for( size = 0, listPointer = list; 
        listPointer; listPointer = listPointer->next, size++ ){
        
    }

    intList = (int *)malloc( sizeof( int ) * size );

    for( i = 0, listPointer = list; listPointer; 
        listPointer = listPointer->next, i++ ){
        intList[i] = listPointer->content;
    }

    max = incompatibleFunction( intList, size );

    free( intList );

    return max;
}

This function calls the adapter function.

int driver(){
    Node * list = 0; //make some list
    int sum = 0;
    int max = 0;

    sum = sum( list );

    //does not work, input parameter does not match
    //max = max( list );

    max = maxAdapter( list );
    
    return 0;
}

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.