2013-08-24 40 views
-1

正如話題自己說的,這是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(); 
} 

Live example

我知道,我並不需要的寬度和高度繪製圓。 (我稍後需要它們來選擇那個圓圈,所以它不是錯誤的:))

+0

如果您的投票請至少留下解釋爲什麼... – Srle

+1

我沒有投票,但這個問題沒有表現出任何努力,也沒有表現出對主題的任何理解。你基本上貼了一段代碼,並說:「_true或false,這使用模式X_」。 – jahroy

+0

我認爲這不是代碼的「牆」,例子就足以被審查幾分鐘。無論如何,謝謝你的建議。 – Srle

回答

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

順便說一句,不要讓你的類是指全局變量。把它當作屬性或參數。