【发布时间】:2013-08-24 01:06:41
【问题描述】:
正如主题本身所说,这是 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();
}
我知道画圆不需要宽度和高度。 (我稍后会需要它们来选择那个圆圈,所以这不是错误的:))
【问题讨论】:
-
如果您投反对票,请至少说明原因...
-
我没有投反对票,但这个问题没有表现出任何努力,也没有表现出对主题的任何理解。你基本上贴了一面代码墙并说:“true or false, this uses pattern X”。
-
我认为这不是代码的“墙”,示例只需几分钟即可查看。无论如何,谢谢你的建议。
-
你说得对:“代码墙”有点苛刻。就像我说的,我没有投反对票。
-
您是否阅读过投反对票的工具提示?它以“这个问题没有显示任何研究工作”开头。那么,您会认为这个问题确实显示了任何研究工作吗?
标签: javascript oop design-patterns