Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Strategy Pattern

Part of TutorialDesignPatterns

Description

Examples of implementing the Gang of Four Strategy Pattern. You can find description on: http://en.wikipedia.org/wiki/Strategy_pattern

Example : Strategy Pattern

/*
 * This source code shows how to code Strategy Pattern
 * in D programming language
 * And also shows how constructor and destructor works
 * in strategy pattern
 *
 */

import std.stdio;

interface Strategy {

	void performOperation();

}

class Algorithm1 : Strategy {

	this() { writefln("Algorithm1 created"); }
	~this() { writefln("Algorithm1 destroyed"); }
	
	void performOperation() { 
		writefln("Algorithm 1's Operation");
	}
	
}

class Algorithm2 : Strategy {
	
	this() { writefln("Algorithm2 created"); }
	~this() { writefln("Algorithm2 destroyed"); }
	
	void performOperation() {
		writefln("Algorithm 2's Operation");
	}
	
}

class Context {

	private Strategy instance;
	
	this(Strategy s) { this.instance = s; }	
	~this() { writefln("Context destroyed"); }
	
	void performAlgorithm() {
		this.instance.performOperation();
	}
}

int main() {
	Context c;
	
	writef("[0] Algorithm 1\n[1] Algorithm 2\nAlgorithm: ");
	uint input;
	
	scanf("%i", &input);
	
	if (input == 0) {
		c = new Context(new Algorithm1);
		c.performAlgorithm(); // must print "Algorithm 1's Operation"
	} else if (input == 1) {
		c = new Context(new Algorithm2);
		c.performAlgorithm(); // must print "Algorithm 2's Operation"
	} else {
		writefln("Invalid input! Program will now terminate...");
	}
	return 0;
}