0

私は、すべて同じクラスのさまざまな種類の敵を持つAndroidゲームを持っています(単一のオブジェクトプールを持つことができるように)。これらの敵が構築されると、実行時にさまざまな異なるプロパティが与えられます。これには、従うべき動作アルゴリズムが含まれます。現在、次のようになっています。

public MoveableEntity build(float positionX, float positionY, MoveableEntityType type,
        int moveLogic, MoveableEntityType weaponType,
        int firePattern, int fireLogic) {

            //Take all the passed in arguments and build an entity

    }

現在、ゲームの更新ループで、各エンティティはいくつかのマネージャーを通過し、エンティティが実行しているロジックのタイプをチェックし、その動作を指示します。

public void updateEntity(MoveableEntity e) {
    switch (e.getiLogic()) {

    case STRAIGHT_LINE_MOVEMENT:
        straightLineMovement(e);
        break;
    case RANDOM_MOVING_LEFT:
        randomMovingLeft(e);
        break;
    case ADVANCE_THEN_RETREAT:
        advanceThenRetreat(e);
        break;
    case RUSH_THEN_RETREAT:
        rushThenRetreat(e);
        break;
                   //lots of logic types
            }

このパターンは、ゲーム全体でかなり一般的になっています (移動ロジック、攻撃方法/タイミングの選択など)。戦略パターンのようなものを使用することを検討したので、次のように言えます。

public MoveableEntity build(float positionX, float positionY, MoveableEntityType type,
    MoveLogic moveLogic...) {

    this.moveLogic = moveLogic;
        //Take all the passed in arguments and build an entity

}

public void update() {
    //do some updating

   //execute assigned AI
   moveLogic.execute(this);

   //other stuff
  }

これは素晴らしいことですが、エンティティが使用するさまざまな種類の AI コンポーネントすべてに対して、大量の追加クラスを作成することになります。基本的に私の質問は次のようになります: このシナリオで、多くの新しいオブジェクトを作成/破棄する必要がない (したがって、パフォーマンスが低下する可能性がある) OO フレンドリーなソリューションを実装する方法はありますか? このシナリオのいくつかの switch ステートメントは問題ありませんか? 私のアプローチはどうあるべきですか?

4

4 に答える 4

0

MoveLogic クラスにはシングルトン パターンを使用できます。

this.moveLogic = new MoveLogic();

以下を使用できます。

this.moveLogic = MoveLogic.getInstance();

したがって、各 MoveLogic クラスに 1 つの MoveLogic オブジェクトのみを割り当てます。

于 2013-07-29T08:20:47.960 に答える
0

大量の余分なクラスが作成されるのを防ぐために、移動ロジック戦略のファクトリ クラスを作成できます。

public class MoveLogicFactory{

    public static MoveLogic createStraightLineMovementLogic(){
        //return a an anonymous inner class of type MoveLogic
        return new MoveLogic(){
            //apply your codes for this specific move logic
        }
    }

    public static MoveLogic createRandomMovingLeftLogic(){
        //... do the same as the first method
    }

    public static MoveLogic createAdvanceThenRetreatLogic(){
        //... do the same as the first method
    }

    public static MoveLogic createRushThenRetreatLogic(){
        //... do the same as the first method
    }
}
于 2013-07-29T08:31:31.407 に答える