正如主题本身所说,这是 Javascript 中策略模式的示例吗?
(我认为问题更适合 codereview,但他们在 stackoverflow 上重定向了我)
var canvas = {
context: document.getElementById("canvas").getContext("2d")
};
///////////////////////////////////////////////////
function Square(_strategy) {
this.x = 50;
this.y = 50;
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();
}
我知道画圆不需要宽度和高度。(我稍后会需要它们来选择那个圆圈,所以这不是错误的:))