Article 136 - Design Pattern - Strategy 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 strategy design pattern example.

It is recommended that the reader review the concepts by reviewing the section Strategy 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.

This is the base class, an interface, that concrete classes will implement. The dynamic runtime swapping occurs through the interface of this class.

class Sort{
    public:
    virtual int sort( Node * list ) = 0;
}

Concrete classes that implement the interface with different functionalities.

In this implementation, we use the Node structure from the Link List Article, see Article 89 - Quicksort Implementation.
In this implementation, we use the Node structure from the Link List Article, see Article 103 - Bubble Sort Implementation.
class QuickSort: public Sort{
    public:
    int sort( Node * list ){
        quicksort( list );
    }
}

class BubbleSort: public Sort{
    public:
    int sort( Node * list ){
        bubbleSort( list );
    }
}

The different implementation can be dynamically swapped during runtime.

enum SortType{
    QUICKSORT = 0,
    BUBBLESORT = 1,
}
int main(){
    int sortType = QUICKSORT; //select a sort type
    Node * list;
    //make arbitrary list

    switch( sortType ){
        case QUICKSORT:
            new QuickSort()->sort( list );
            break;
        case BUBBLESORT:
            new BubbleSort()->sort( list );
            break;
        default:
        return -1;        
    }

    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.