-2

トピック自体が言うように、これは Javascript での戦略パターンの例ですか?

(質問はコードレビューに適していると思いますが、スタックオーバーフローでリダイレクトされます)

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();
}

実際の例

円を描くのに幅と高さは必要ないことを知っています。(後でその円を選択するために必要になるので、間違いではありません:))

4

1 に答える 1

3

はい。しかし、そのようなパターンは 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);
};

ところで、クラスにグローバル変数を参照させないでください。プロパティまたはパラメータとして取得します。

于 2013-08-24T16:05:13.037 に答える