繁体   English   中英

我如何使用静态方法来增加非静态变量?

[英]How would I use a static method to increase a non-static variable?

我有一个名为Game的Java类,它有一个名为score的非静态整数。

我想实现一个静态方法,它将每个Game对象的得分增加1,名为increaseAllScore()。 这可能吗? 我能模拟这样的事情还是有什么方法可以解决这个问题?

你可以用这样的实现来做到这一点:

int score;
static int scoremodifier;

public static void increaseAllScore() {
    scoremodifier++;
}

public int getScore() {
    return score + Game.scoremodifier;
}

唯一的方法是为静态方法提供一种机制来访问对Game对象的引用。 一种方法是让每个Game对象在静态数据结构中注册。

例如,您可以这样做:

public class Game {
    private static Set<WeakReference<Game>> registeredGames
        = new HashSet<WeakReference<Game>>();
    private int score;

    public Game() {
        // construct the game
        registeredGames.add(new WeakReference(this));
    }

    . . .

    public static incrementAllScores() {
        for (WeakReference<Game> gameRef : registeredGames) {
            Game game = gameRef.get();
            if (game != null) {
                game.score++;
            }
        }
    }
}

我在这里使用WeakReference<Game> ,这样当没有其他引用时,该集合不会阻止游戏被垃圾收集。

这在技术上是可行的,但它通常是一个糟糕的设计* 而是为您的所有游戏(称为class Games )创建一个容器,该容器将保存对所有已创建的Game实例的引用。 很可能Games类将使用createGame()方法来完全控制所有创建的游戏的生命周期。

一旦你有了Games类,它就可以有非静态的increaseAllScores()方法,它基本上遍历所有创建的Game实例并逐个增加所有这些实例的得分。

* - 创建所有实例的static List<Game>并在Game构造函数中修改该列表。

这将是您的问题的解决方案的大纲:

static final List<Game> games = new ArrayList<>();

public class Game {
  public Game() {
    games.add(this);
  }
}

public static void increaseAllScore() {
  for (Game g : games) game.increaseScore();
}

这是可能的,但需要一些簿记。 实质上,你必须保持一组指向所有现有游戏的静态指针。 在游戏的构造函数中,您需要将其添加到此列表中,并且需要在析构函数中再次将其删除。

一个可能更好的方法是使用一个名为scoreOffset或类似的静态变量。 然后,您可以通过获取实例分数并添加静态scoreOffset来计算游戏的分数。

如果您的increaseAllScore方法具有对Game实例的静态访问权限(您可以在参数中传入列表,或者具有静态存储的列表),则只能执行此操作。

这不可能; 首先学习面向对象编程的基础知识。

作为一个工作广告,你可以参考所有的游戏:

public class Game {
    private static List<Game> allGames = new ArrayList<Game>();

    public Game createNewGame() {
        Game game = new Game();
        allGames.add(game); 
        return game;
    }

    public static void increaseAllGames() {
        for (Game game : games) {
            game.increaseScore(); 
        }
    }    
}

这只是一个实现示例; 对于设计我不会把它们放在同一个类中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM