Skip to content

Design Pattern: Command Method

fahimc edited this page Mar 10, 2013 · 1 revision

##Definition Allows you to centralise actions and process them.

##How To

###1. Create an Interface

var ICommand = {
	execute : function(a, b) {
	}
};

###2. Create Command Classes Which implements the Interface and overrides the execute function. Add different actions for the data.

var AddCommand = function() {
	this.execute = function(a, b) {
	return a + b;
	}
};
Class.implement(AddCommand, ICommand);

var SubCommand = function() {
	this.execute = function(a, b) {
	return a - b;
	}
};
Class.implement(SubCommand, ICommand);

###3. Create an Command Bus which will create a command on demand depending on the type.

var CommandBus = {
	action : function(type, a, b) {
	this.command = null;
	switch(type) {
	case 'add':
	command = new AddCommand();
	break;
	case 'subtract':
	command = new SubCommand();
	break;

	}
	return command.execute(a, b);
	delete this.command;
	}
};

###4. Test Log the actions

console.log(CommandBus.action('add', 2, 2));
console.log(CommandBus.action('subtract', 2, 2));

Clone this wiki locally