Strategy - shoonie/StudyingDesignPattern GitHub Wiki

Intent

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Diagram

disgram

Consequences

  1. Families of related algorithms.
  2. An alternative to subclassing.
  3. Strategies eliminate conditional statements.
  4. A choice of implementations.
  5. Clients must be aware of different Strategies.
  6. Communication overhead between Strategy and Context.
  7. Increased number of objects.

Implementation

  1. Defining the Strategy and Context interfaces.
  2. Strategy as template parameters.
  3. Making Strategy objects optional.

Sample Code

//http://www.bogotobogo.com/DesignPatterns/strategy.php
#include <iostream>
using namespace std;

class SortBehavior
{
public:
	virtual void sort() const = 0;
};

class Merge : public SortBehavior
{
public:
	virtual void sort() const {
		cout << "Merge sort()\n";
	}
};

class Quick : public SortBehavior {
public:
	virtual void sort() const {
		cout << "Quick sort()\n";
	}
};

class Heap : public SortBehavior
{
public:
	virtual void sort() const {
		cout << "Heap sort()\n";
	}
};

class SearchBehavior
{
public:
	virtual void search() const = 0;
};

class Sequential : public SearchBehavior
{
public:
	virtual void search() const {
		cout << "Sequential search()\n";
	}
};

class BinaryTree : public SearchBehavior
{
public:
	virtual void search() const {
		cout << "BinaryTree search()\n";
	}
};

class HashTable : public SearchBehavior
{
public:
	virtual void search() const {
		cout << "HashTable search()\n";
	}
};

// Context
class Collection
{
private:
	SortBehavior * m_sort;
	SearchBehavior* m_search;
public:
	Collection() {}
	void set_sort(SortBehavior* s) {
		m_sort = s;
	}
	void set_search(SearchBehavior* s) {
		m_search = s;
	}
	void sort() const {
		m_sort->sort();
	}
	void search() const {
		m_search->search();
	}
};


int main(int argc, char *argv[])
{
	Merge merge;
	Quick quick;
	Heap heap;

	Sequential sequential;
	BinaryTree binaryTree;
	HashTable hashTable;

	Collection colA;
	colA.set_sort(&merge);
	colA.sort();

	Collection colB;
	colB.set_search(&binaryTree);
	colB.search();

	return 0;
}
⚠️ **GitHub.com Fallback** ⚠️