【问题标题】:Example, is this strategy pattern? [closed]例如,这是策略模式吗? [关闭]
【发布时间】: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();
}

Live example

我知道画圆不需要宽度和高度。 (我稍后会需要它们来选择那个圆圈,所以这不是错误的:))

【问题讨论】:

  • 如果您投反对票,请至少说明原因...
  • 我没有投反对票,但这个问题没有表现出任何努力,也没有表现出对主题的任何理解。你基本上贴了一面代码墙并说:“true or false, this uses pattern X”。
  • 我认为这不是代码的“墙”,示例只需几分钟即可查看。无论如何,谢谢你的建议。
  • 你说得对:“代码墙”有点苛刻。就像我说的,我没有投反对票。
  • 您是否阅读过投反对票的工具提示?它以“这个问题没有显示任何研究工作”开头。那么,您会认为这个问题确实显示了任何研究工作吗?

标签: javascript oop design-patterns


【解决方案1】:

是的,但是这种模式在 Javascript 中可以很简单地实现,甚至可能不是一个模式。

基本上即使你是这样的:

function Square() {
    this.x = 50;
    this.y = 50;
    this.width = 100;
    this.height = 100;
}

Square.prototype.draw = function(canvas) {
    canvas.context.strokeRect(this.x, this.y, this.width, this.height);
};

你可以这样做:

var a = new Square();
a.draw = function(canvas) {
    canvas.context.strokeRect(this.x + 5, this.y, this.width, this.height);
};

顺便说一句,不要让你的类引用全局变量。将其作为属性或参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    相关资源
    最近更新 更多