Command Dispatching Architecture

COMP 310    Java Resources  Eclipse Resources

[Back to Ballworld]

Overview


Command-Driven Dispatching

For reference, please see the Command-dispatching Architecture with Inter-ball Interactions command-dispatching Ballworld with inter-ball interactions demo.     Note:  This is the functionality that you will be creating for HW05, not HW04.  In HW04, the command dispatching will be implemented, but only to the extent of replicating the existing updating and new painting behaviors.

As discussed at the end of the last lecture, the dispatcher shouldn't be considered simply as the conveyor of a single message to the balls, "update!".     One problem that arises out of that viewpoint is that the painting and the state updating processes are coupled together, resulting in artifacts such as the simulation speeding up whenever the frame is resized or an animated GIF is used. 

The dispatcher should send a message (a "command") object to the balls.

But since the ball has no idea a priori what that command is, the only thing that the ball can do is to delegate the interpretation of that command to the one object that knows unequivocally what the command is...the command itelf.

The ball delegates to the command to perform the processing associated with that command.

The balls can be made to do anything one desires simply by sending the appropriate message to them.

Definition:

Strategy -- an abstract behavior/processing that is used by a context object for a specific purpose, e.g. it is used with a known semantic.    Painting and updating the state of the ball are strategies.

Command -- and abstract behavior/processing that is used by the context object without a specific purpose, without a specific semantic.   All the context knows is when to run the command, e.g. whenever it is called to update.  But the context never needs to know what the command is really doing.   Typically, because of the lack of semantic, the command will either have a void return or the context will simply pass any returned values on to something else without doing any additional processing on them -- it can't because the context doesn't know what the results are.

 

Reference: Ballworld provided code (Includes documentation about the IDispatcher and IObserver interfaces and implementations)

Command-Based Updating

Instead of merely telling the ball to perform an invariant update method (single method to move, paint, bounce, etc) with an invariant parameter (the Graphics object) being passed, the dispatcher sends out a variant command object that the ball invariantly executes.

A command to the ball to do something is defined as such:

package ballworld.model;

/**
 * Interface that represents commands sent through the dispatcher to process the balls
 * 
 */
@FunctionalInterface
public abstract interface IBallCmd {
    /**
     * The method run by the ball's update method which is called when the ball is updated by the dispatcher.
     * @param context The ball that is calling this method.   The context under which the command is to be run.
     * @param disp The Dispatcher that sent the command out.
     */	
    public abstract void apply(Ball context, IDispatcher<IBallCmd> disp);
}

For instance, the dispatcher may send out a command to update the state:

_dispatcher.updateAll(_updateStateCmd);

An anonymous inner class can be used above for the IBallCmd implementation without any loss of generality.  A typical dispatch using an anoymous inner class would look something like:

_dispatcher.updateAll(new IBallCmd() {

	@Override
	/**
	 * Do stuff with the ball
	 */
	public void apply(Ball context, IDispatcher<IBallCmd> disp) {
		// Whatever you want to do with the context Ball!			
	}				
});

// Or more simply, using lambda expressions:

_dispatcher.updateAll( (context, disp)->{
                                             // Whatever you want to do with the context Ball!
                                        });
                                        

How do you think that anonymous inner classes can be used to communicate additional information (i.e. additional input parameters) to the balls?   Remember that the one free parameter that updateAll() used to accept is now taken up with the command being passed!

All the ball ever does is to run the command, passing itself and the Dispatcher:

/**
 * The update method called by the main ball Dispatcher to notify all the balls to perform the given command.
 * The given command is executed.
 * @param o The Dispatcher that sent the update request.
 * @param cmd The IBallCmd that will be run.
 */
public void update(IDipatcher<IBallCmd> disp, IBallCmd cmd) {
    cmd.apply(this, disp);
}

What would the method body of an IBallCmd.apply() implementation look like if you

With this, a ball can be made to do whatever you want it to do, whenever you want it to do it!

 

Switching Over To Command-based Dispatching

For now, let's just replicate our current behavior but with a command-based dispatching.

  1. Using the constructs above, change the update code of your ball to take an IBallCmd as its input parameter that it then simply "applies".  
  2. Change the code of in the model for the call to the dispatcher's updateAll method.   Use an anonymous inner class (or lambda expression) to define the IBallCmd to be sent to the balls (Why do we need an anonymous inner class or lambda expression here?)     Where do you think the code that used to be in the ball's update method now resides?

When you are done, your BallWorld system should run identically as before, but with a new door open to even more possibilities!

Did you have to touch your view code at all?   The controller code?   Why or why not?

For the adventurous: By installing a second Timer object, can you decouple the painting process from the updating of the ball state?   In doing so, can you fix the problem of resizing and animated GIFs affecting the behavior of the balls?

Making Balls Talk to Eachother

Above, we saw that sending commands to the balls enables us to make them do anything the model wants them to do.   But does it matter who sent the command?   What if it was another ball that sent the command?   Couldn't that ball make the other balls do something?  Or the sending ball be affected by the other balls?

All we need to do is to enable a ball to get a hold of the IDispatcher.   If it has that, it can send out a command just like the model.

With two simple changes to our current system, we can modify the Ball's updateState method and the IUpdateStrategy.updateState method to take the IDispatcher as an input parameter.   The latter change will unfortunately instigate a rather tedious chore of modifying all the concrete IUpdateStrategy implementations.  (Can you explain this phenomenon in terms of variant/invariant?).

The update strategy is modified to accept the IDispatcher:

public interface IUpdateStrategy {
	/**
	 * Update the state of the context Ball.
	 * @param context  The context (host) Ball whose state is to be updated
	 * @param dispatcher  The Dispatcher who sent the command that is calling through to here.
	 */
	public abstract void updateState(Ball context, IDispatcher<IBallCmd> dispatcher);
}

In the Ball, we pass the Dispatcher along to the update strategy.   The IBallCmd is responsible for passing it to the Ball's updateState method.

/**
 * Update the state of the ball.   Delegates to the update strategy.
 * @param dispatcher The Dispatcher that sent the command that is calling this method.
 */
public void updateState(IDispatcher<IBallCmd> dispatcher){
	_updateStrategy.updateState(this, dispatcher); // update this ball's state using the strategy.		
}

Now an IUpdateStrategy is free to send commands out through the dispatcher to all the other ball -- including itself.

Always check if you are receiving your own command!

Consider the following update strategy that spawns new balls when a ball contacts another.:

public class SpawnStrategy implements IUpdateStrategy {

	private int count = 0; // tick counter that counts out the delay before another ball can be spawned.
	private int delay = 100;  // tick delay which increases at each spawn to keep total spawn rate from exponentially exploding.

	@Override
	public void updateState(final Ball context, IDispatcher<IBallCmd> dispatcher) {
	
		if (delay < count++) {
			dispatcher.updateAll(new IBallCmd() {

				@Override
				public void apply(Ball other, IDispatcher<IBallCmd> disp) {

					if (count != 0 && context != other) {
						if ((context.getRadius() + other.getRadius()) > 
						    context.getLocation().distance(other.getLocation())) {
							disp.addObserver(new Ball(
									new Point(context.getLocation()), 
									context.getRadius(),
									new Point(-context.getVelocity().x+1,-context.getVelocity().y+1), 
									context.getColor(),
									context.getContainer(), 
									new SpawnStrategy(), 
									context.getPaintStrategy()));
							count = 0;
							delay *= 5;
						}
					}
				}

			});
		}
	}

}

// Or, using lambda expressions:
public class SpawnStrategy implements IUpdateStrategy {

	private int count = 0;
	private int delay = 100;

	@Override
	public void updateState(final Ball context, IDispatcher<IBallCmd> dispatcher) {

		if (delay < count++) {
			dispatcher.updateAll((other, disp) -> {

					if (count != 0 && context != other) {
						if ((context.getRadius() + other.getRadius()) > context
								.getLocation().distance(other.getLocation())) {
							disp.addObserver(new Ball(
									new Point(context.getLocation()), 
									context.getRadius(),
									new Point(-context.getVelocity().x+1,-context.getVelocity().y+1), 
									context.getColor(),
									context.getContainer(), 
									new SpawnStrategy(), 
									context.getPaintStrategy()));
							count = 0;
							delay *= 5;
						}
					}
				}
			);
		}
	}

}

Even more fun...

For those that would like to add keyboard interactivity to their Ballworld or any other system, please see the page on Using Lambdas for Asynchronous Updating and Key Binding with Action Maps

 

 

© 2020 by Stephen Wong