2013-07-17 2 views
0

다음은 다양한 게임에서 사용되는 여러 엔진 구현에 대해 균형 청취자 등록을 처리하는 기본 엔진 클래스를 제공하는 작업 Java 코드입니다. 예 : 데모 게임을위한 데모 밸런스와 백 오피스 등에서 균형을 잡는 동일한 엔진의 현금 버전을 유지하는 데모 엔진이있을 것입니다. 여기 핵심은 실제 자바가 아니라 패턴의 이런 종류를 구현하는 방법입니다 자바 스크립트에서. 나는 John Resigs "simple JavaScript inheritance"와 "JavaScript : The Definitive Guide"에 정의 된 extends() 설탕을 사용하여 다양한 모듈 패턴을 사용하는 등 약 30 가지 방법을 시도했다. 이 문제를 해결하기 위해 노력했습니다.상속을 사용하여이 자바 패턴을 JavaScript로 구현하는 방법은 무엇입니까?

파일 Engine.java : 여기

는 작업 자바 코드

package com.test; 
public abstract class Engine { 
    BalanceListener externalBalanceListener = null; 
    double balance = 0; 
    public void registerBalanceListener(BalanceListener balanceListener) { 
     externalBalanceListener = balanceListener; 
     balanceListener.update(balance); // call once when first register 
    } 
    public double getBalance() { 
     return balance; 
    } 
    protected void setBalance(double newBal) { 
     if (newBal != balance) { 
      balance = newBal; 
      if (externalBalanceListener != null) { 
       externalBalanceListener.update(newBal); 
      } 
     }  
    } 
    public abstract double startGame(double stake, int numLines); 
} 

파일 BalanceListener.java

package com.test; 
public interface BalanceListener { 
    void update(double balance); 
} 

파일 DemoEngine.java

package com.test; 
import java.util.Random; 

public class DemoEngine extends Engine { 
    public DemoEngine() { 
     setBalance(10000); 
    } 
    public double startGame(double stake, int numLines) { 
     double wonAmount; 
     Random random = new Random(); 

     setBalance (getBalance() - (stake * numLines)); 

     // some game logic 
     wonAmount = Math.round((random.nextDouble() * 10)) * stake; 
     setBalance (getBalance() + wonAmount);   
     return wonAmount; 
    } 
} 

파일 DemoGame.java

package com.test; 

public class DemoGame { 

    public class MyListener implements BalanceListener { 
     public MyListener(){ 
     } 
     public void update(double balance) { 
      System.out.println("new balance: " + balance); 
     } 
    } 

    public static void main(String[] args) { 
     Engine engine = new DemoEngine(); 

     DemoGame demoGame = new DemoGame(); 

     BalanceListener balanceListener = demoGame.new MyListener(); 

     engine.registerBalanceListener(balanceListener); 

     engine.startGame(10, 20); 
    } 
} 
다음

일반은 (실패) 분명히

function Engine() { 
    this.balance = 0; 
    this.externalBalanceListener; 

    this.registerBalanceListener = function(l) { 
      this.externalBalanceListener= l; 
      this.externalBalanceListener(this.balance); 
    }; 

    this.getBalance = function() { 
     return this.balance; 
    }; 

    this.setBalance = function (newBal) { 
     if (newBal != this.balance) { 
      this.balance = newBal; 
      if (this.externalBalanceListener != undefined) { 
       this.externalBalanceListener(newBal); 
      } 
     } 
    }; 

}; 

function DemoEngine() { 
    this.startGame = function(stake, numLines) { 
     var won; 

     setBalance(this.getBalance() - stake*numlines); 
     won = Math.round(Math.random() * 10) * Stake; 

     this.setBalance(this.getBalance() + won); 

     return won; 
    }; 
} 

DemoEngine.prototype = Engine; 

function DemoGame() { 

    function balanceListener(balance) { 
     console.log(balance); 
    } 

    var engine = new DemoEngine(); 

    engine.registerBalanceListener(balanceListener); // This throws an exception: Uncaught TypeError: Object [object Object] has no method 'registerBalanceListener' 

    engine.startGame(10, 25); 
} 

var game = new DemoGame(); 

내가 어떤이 (http://jsfiddle.net/fmX67/ 참조) 자바 스크립트에서 작업 같은 일을 얻기 위해 시도였다 내가하고있는 아이디어 (여러 개의 JS 서적을 읽음에도 불구하고). 저는 상속을 시도하는 대신 컴포지션을 사용할 수 있다고 가정합니다. 그러나 이것은 언어의 사용과 구현할 수있는 패턴을 제한합니다.

편집 : 여기 Shaun West의 답변이있는 작업 버전입니다. 이에

DemoEngine.prototype = Engine; 

:

DemoEngine.prototype = new Engine(); 

이는 자바에서 오는 사람에게 보일 수만큼 이상한 http://jsfiddle.net/fmX67/3/

function Engine() { 
    this.balance = 0; 
    this.externalBalanceListener; 

    this.registerBalanceListener = function(l) { 
      this.externalBalanceListener= l; 
      this.externalBalanceListener(this.balance); 
    }; 

    this.getBalance = function() { 
     return this.balance; 
    }; 

    this.setBalance = function (newBal) { 
     if (newBal != this.balance) { 
      this.balance = newBal; 
      if (this.externalBalanceListener != undefined) { 
       this.externalBalanceListener(newBal); 
      } 
     } 
    }; 

}; 

function DemoEngine() { 
    this.setBalance(1000); 
    this.startGame = function(stake, numLines) { 
     var won; 

     this.setBalance(this.getBalance() - stake*numLines); 
     won = Math.round(Math.random() * 10) * stake; 

     this.setBalance(this.getBalance() + won); 

     return won; 
    }; 
} 

DemoEngine.prototype = new Engine(); 

function DemoGame() { 

    function balanceListener(balance) { 
     console.log(balance); 
    } 

    var engine = new DemoEngine(); 

    engine.registerBalanceListener(balanceListener); // This throws an exception: Uncaught TypeError: Object [object Object] has no method 'registerBalanceListener' 

    engine.startGame(10, 25); 
} 


var game = new DemoGame(); 
+0

이것은 많은 코드처럼 보이지 않습니다 ... – Amberlamps

+0

지금까지 무엇을 했습니까? – turnt

답변

1

를 참조하십시오 시도에이를 변경할 수 있습니다 더 많은 정보를 원한다면 대답은 꽤 좋습니다 : What is the 'new' keyword in JavaScript?

+0

결과, 그게 효과가! 여전히 고전적인 (뚫을 수없는) JS 서적과 기사를 넘어 가고 있음에도 불구하고 JS 계승에 의해 여전히 당황 스럽다. 내 두뇌는 동시에 필요한 모든 JS 언어 개념을 얻을만큼 충분히 크지 않다 (자바 상속은 비교에 의해 사소하다). –

관련 문제