Files
java-design-patterns/update-method
Ilkka Seppälä 6cd2d0353a docs: Content SEO updates (#2990)
* update yaml frontmatter format

* update abstract document

* update abstract factory

* use the new pattern template

* acyclic visitor seo

* adapter seo

* ambassador seo

* acl seo

* aaa seo

* async method invocation seo

* balking seo

* bridge seo

* builder seo

* business delegate and bytecode seo

* caching seo

* callback seo

* chain seo

* update headings

* circuit breaker seo

* client session + collecting parameter seo

* collection pipeline seo

* combinator SEO

* command seo

* cqrs seo

* commander seo

* component seo

* composite seo

* composite entity seo

* composite view seo

* context object seo

* converter seo

* crtp seo

* currying seo

* dao seo

* data bus seo

* data locality seo

* data mapper seo

* dto seo

* decorator seo

* delegation seo

* di seo

* dirty flag seo

* domain model seo

* double buffer seo

* double checked locking seo

* double dispatch seo

* dynamic proxy seo

* event aggregator seo

* event-based asynchronous seo

* eda seo

* event queue seo

* event sourcing seo

* execute around seo

* extension objects seo

* facade seo

* factory seo

* factory kit seo

* factory method seo

* fanout/fanin seo

* feature toggle seo

* filterer seo

* fluent interface seo

* flux seo

* flyweight seo

* front controller seo

* function composition seo

* game loop seo

* gateway seo

* guarded suspension seo

* half-sync/half-async seo

* health check seo

* hexagonal seo

* identity map seo

* intercepting filter seo

* interpreter seo

* iterator seo

* layers seo

* lazy loading seo

* leader election seo

* leader/followers seo

* lockable object seo

* rename and add seo for marker interface

* master-worker seo

* mediator seo

* memento seo

* metadata mapping seo

* microservice aggregator seo

* api gw seo

* microservices log aggregration seo

* mvc seo

* mvi seo

* mvp seo

* mvvm seo

* monad seo

* monitor seo

* monostate seo

* multiton seo

* mute idiom seo

* naked objects & notification seo

* null object seo

* object mother seo

* object pool seo

* observer seo

* optimistic locking seo

* page controller seo

* page object seo

* parameter object seo

* partial response seo

* pipeline seo

* poison pill seo

* presentation model seo

* private class data seo

* producer-consumer seo

* promise seo

* property seo

* prototype seo

* proxy seo

* queue-based load leveling seo

* reactor seo

* registry seo

* repository seo

* RAII seo

* retry seo

* role object seo

* saga seo

* separated interface seo

* serialized entity seo

* serialized lob seo

* servant seo

* server session seo

* service layer seo

* service locator seo

* service to worker seo

* sharding seo

* single table inheritance seo

* singleton seo

* spatial partition seo

* special case seo

* specification seo

* state seo

* step builder seo

* strangler seo

* strategy seo

* subclass sandbox seo

* table module seo

* template method seo

* throttling seo

* tolerant reader seo

* trampoline seo

* transaction script seo

* twin seo

* type object seo

* unit of work seo

* update method seo

* value object seo

* version number seo

* virtual proxy seo

* visitor seo

* seo enhancements

* seo improvements

* SEO enhancements

* SEO improvements

* SEO additions

* SEO improvements

* more SEO improvements

* rename hexagonal + SEO improvements

* SEO improvements

* more SEO stuff

* SEO improvements

* SEO optimizations

* SEO enhancements

* enchance SEO

* improve SEO

* SEO improvements

* update headers
2024-06-08 19:54:44 +03:00
..
2024-05-23 10:05:40 +03:00
2022-09-14 23:22:24 +05:30
2024-06-08 19:54:44 +03:00

title, shortTitle, description, category, language, tag
title shortTitle description category language tag
Update Method Pattern in Java: Enhancing Game Loop Efficiency with Systematic Updates Update Method Explore the Update Method design pattern for Java, ideal for real-time games and applications. Learn how it optimizes performance by updating objects frame-by-frame to maintain synchronized, efficient operations. Behavioral en
Abstraction
Data processing
Decoupling
Event-driven
Game programming
Polymorphism

Also known as

  • Update Mechanism

Intent of Update Method Design Pattern

The Update Method pattern in Java simulates a collection of independent objects by telling each to process one frame of behavior at a time.

Detailed Explanation of Update Method Pattern with Real-World Examples

Real-world example

A real-world example of the Update Method design pattern is a weather monitoring system. In this system, multiple display devices (such as a mobile app, a website widget, and a wall-mounted digital display) need to show the current weather conditions. These displays subscribe to updates from a central weather station, which collects data from various sensors (temperature, humidity, wind speed, etc.). When the weather station detects new data, it triggers an update method that pushes the new information to all subscribed display devices, ensuring they all show the latest weather conditions simultaneously. This ensures that all displays are synchronized and updated without the need for each device to independently check for updates.

In plain words

The Update Method design pattern processes system object behavior one frame at a time

gameprogrammingpatterns.com says

The game world maintains a collection of objects. Each object implements an update method that simulates one frame of the objects behavior. Each frame, the game updates every object in the collection.

Programmatic Example of Update Method Pattern in Java

The Update Method design pattern is a behavioral pattern that simulates a collection of independent game or application objects by telling each to process one frame of behavior at a time. This pattern is commonly used in game development, where each object in the game world needs to be updated once per frame.

The World class represents the game world. It maintains a list of entities (List<Entity> entities) and a boolean flag (isRunning) to indicate whether the game is running.

public class World {

  protected List<Entity> entities;
  protected volatile boolean isRunning;

  public World() {
    entities = new ArrayList<>();
    isRunning = false;
  }
  // Other properties and methods...
}

The gameLoop method is the main game loop. It continuously processes user input, updates the game state, and renders the next frame as long as the game is running.

private void gameLoop() {
  while (isRunning) {
    processInput();
    update();
    render();
  }
}

The processInput method simulates handling user input. In this case, it simply introduces a random time lag to simulate real-life game situations.

private void processInput() {
  try {
    int lag = new SecureRandom().nextInt(200) + 50;
    Thread.sleep(lag);
  } catch (InterruptedException e) {
    LOGGER.error(e.getMessage());
    Thread.currentThread().interrupt();
  }
}

The update method is where the Update Method pattern is implemented. It iterates over all entities in the game world and calls their update method, allowing each entity to process one frame of behavior.

private void update() {
  for (var entity : entities) {
    entity.update();
  }
}

The render method is responsible for rendering the next frame. In this example, it does nothing as it's not related to the pattern.

private void render() {
  // Does Nothing
}

The run and stop methods are used to start and stop the game loop.

public void run() {
  LOGGER.info("Start game.");
  isRunning = true;
  var thread = new Thread(this::gameLoop);
  thread.start();
}

public void stop() {
  LOGGER.info("Stop game.");
  isRunning = false;
}

The addEntity method is used to add new entities to the game world.

public void addEntity(Entity entity) {
  entities.add(entity);
}

In the App class, we can see how the World class and its methods are used to create a game world, add entities to it, and start the game loop.

@Slf4j
public class App {

    private static final int GAME_RUNNING_TIME = 2000;

    public static void main(String[] args) {
        try {
            var world = new World();
            var skeleton1 = new Skeleton(1, 10);
            var skeleton2 = new Skeleton(2, 70);
            var statue = new Statue(3, 20);
            world.addEntity(skeleton1);
            world.addEntity(skeleton2);
            world.addEntity(statue);
            world.run();
            Thread.sleep(GAME_RUNNING_TIME);
            world.stop();
        } catch (InterruptedException e) {
            LOGGER.error(e.getMessage());
        }
    }
}

Console output:

14:46:33.181 [main] INFO com.iluwatar.updatemethod.World -- Start game.
14:46:33.280 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 11.
14:46:33.281 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 71.
14:46:33.452 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 12.
14:46:33.452 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 72.
14:46:33.621 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 13.
14:46:33.621 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 73.
14:46:33.793 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 14.
14:46:33.793 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 74.
14:46:33.885 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 15.
14:46:33.885 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 75.
14:46:34.113 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 16.
14:46:34.113 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 76.
14:46:34.324 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 17.
14:46:34.324 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 77.
14:46:34.574 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 18.
14:46:34.575 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 78.
14:46:34.730 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 19.
14:46:34.731 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 79.
14:46:34.803 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 20.
14:46:34.803 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 80.
14:46:34.979 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 21.
14:46:34.979 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 81.
14:46:35.045 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 22.
14:46:35.046 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 82.
14:46:35.187 [main] INFO com.iluwatar.updatemethod.World -- Stop game.
14:46:35.288 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 1 is on position 23.
14:46:35.289 [Thread-0] INFO com.iluwatar.updatemethod.Skeleton -- Skeleton 2 is on position 83.

This is a basic implementation of the Update Method pattern. In a real-world application, the Entity class would likely have additional methods and properties, and the update method would contain more complex logic to simulate the entity's behavior.

When to Use the Update Method Pattern in Java

Update Method works well when:

  • Typically applied in scenarios where multiple objects need synchronous updates without the overhead of manual synchronization, making it a go-to for advanced Java developers.
  • The application has a number of objects or systems that need to run simultaneously.
  • Each objects behavior is mostly independent of the others.
  • The objects need to be simulated over time.

Real-World Applications of Update Method Pattern in Java

  • Real-time games and data processing applications where world objects need to be updated once per frame.

Benefits and Trade-offs of Update Method Pattern

Benefits:

  • Each entity encapsulates its own behavior
  • Makes it easy to add and remove entities
  • Keeps the main loop uncluttered

Trade-offs:

  • Increases complexity due to yielding control every frame
  • The state needs to be stored to enable resuming updates after each frame
  • Entities are simulated each frame, but they are not truly concurrent
  • Component: Often used in game development to allow entities to be composed of various components, each potentially having its own update method.
  • Game Loop: Continuously updates game state and renders the game, which may include the Update Method for various game objects.

References and Credits