java - 对 Game 类使用 Singleton 模式

标签 java design-patterns

我正在开发一款使用 HTML5 websockets 和 Java 作为后端的网页游戏。当前为每个玩家创建一个游戏类的新实例,它还创建一个带有计时器任务的计时器来运行游戏循环并每 60fps 向前端发送更新。

由于这些计时器会占用大量玩家在玩的服务器资源,因此我正在考虑在游戏类中应用单例模式并保留一系列比赛。我不会为每个玩家创建一个计时器,而是创建 1 个计时器,用 for 循环为数组中的每场比赛更新游戏循环。

我想知道是否有更好的方法,因为我听说单例模式有很多缺点,特别是对于单元测试。

最佳答案

假设我正确理解了你的问题,你想为所有比赛使用 1 个计时器,并为每场比赛使用 for 循环来更新游戏。

这是一个可怕的想法。沿该线任何位置的任何类型的渲染阻塞都会影响整个服务器。如果第一场比赛中有人向服务器发送大量数据,则会阻塞线程并降低每场比赛的 FPS。

是的,计时器对服务器的负担很重。但是,如果同时有太多 Activity 匹配,则对所有匹配使用一个计时器会导致线程阻塞,因为单个线程无法处理如此高的负载并以 60 FPS 运行。

设计任何给定游戏服务器的最佳方法可能是使用线程。

您可以使用 Thread.sleep 来创建延迟并维持给定的 FPS,并且使用线程而不是计时器来减轻负载。 IT 仍然很重,但使用线程比计时器轻。

至于实际线程,这是它的一部分:

public void run(){


 long lastLoopTime = System.nanoTime();
    final int TARGET_FPS = 60;//The FPS. Can be reduced or increased.
    final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;//1 second = 10^9 nanoseconds
    long lastFpsTime = 0;//Used to calculate delta
    while(running){
        long now = System.nanoTime();//Get the current time
        long updateLength = now - lastLoopTime;//get the time it took to update
        lastLoopTime = now;//set the last time the loop started to the current time
        double delta = updateLength / ((double)OPTIMAL_TIME);//Calculate delta

        lastFpsTime += updateLength;
        if(lastFpsTime >= 1000000000){
            lastFpsTime = 0;
        }

        //Right here you place your code. Update the servers, push and read data, whatever you need

        try{
            long gt = (lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000;//calculate the time to sleep, and convert to milliseconds
            Thread.sleep(gt);//And finally, sleep to maintain FPS
        }catch(InterruptedException e){
        }
    }
}

该类扩展了 Thread 并具有一个名为 running 的 boolean 值。该 boolean 值允许停止线程而不必抛出异常。

为每场比赛创建一个线程(这一点很重要。为每个玩家执行此操作会浪费资源。为所有比赛创建一个线程,除非您有一台 super 计算机,否则不可能保持 60 FPS(取决于匹配的数量)),并有一个用于管理连接和匹配线程的主线程

关于java - 对 Game 类使用 Singleton 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47240725/

相关文章:

c# - 将用例封装在软件中

iphone - iPhone 开发环境中的 MVC

php - 抽象工厂使用 "new"吗?

java - 为什么 HashMap resize 在碰撞或最坏情况下

java - 存储 Android 应用程序列表

java - Android Bundle putStringArray 不工作

java - Struts - <html :errors/> to display error messages in Jsp? 的替代方案

java - Cassandra : Getting read count for Index table in cassandra?

java - Java中的抽象类与接口(interface)

Java:像 Servlet 过滤器一样提供预处理和后处理的设计模式