Friday, 23 August 2013

Example, is this strategy pattern?

Example, is this strategy pattern?

As the topic say by itself, is this example of strategy pattern in
Javascript?
(I think question is more suitable for codereview but they redirect me on
stackoverflow)
var canvas = {
context: document.getElementById("canvas").getContext("2d")
};
///////////////////////////////////////////////////
function Square(_strategy) {
this.x = 200;
this.y = 200;
this.width = 100;
this.height = 100;
this.strategy = _strategy;
}
Square.prototype.draw = function() {
this.strategy(this);
};
///////////////////////////////////////////////////
function Circle(strategy) {
Square.call(this, strategy);
this.radius = 25;
}
Circle.prototype = new Square();
///////////////////////////////////////////////////
function drawSquare(shape) {
canvas.context.strokeRect(shape.x, shape.y, shape.width, shape.height);
}
///////////////////////////////////////////////////
function drawCircle(shape) {
canvas.context.beginPath();
canvas.context.arc(shape.x , shape.y, shape.radius, 0, 360, false);
canvas.context.stroke();
}
///////////////////////////////////////////////////
var shapes = [];
shapes.push(new Square(drawSquare));
shapes.push(new Circle(drawCircle));
for(var i=0; i<shapes.length; i++) {
shapes[i].draw();
}
Live example
I know that i don't need width and height for drawing circle. (I will need
them later for selecting that circle, so it is not mistake :) )

No comments:

Post a Comment