Reputation: 20050
What are the considerations to favor each design?
Suppose i am writing an Input component that gathers input from devices (Mouse, Gamepad, Touch, etc).
One way of designing it would be to supply an API of methods that test a given state at a given point of time (is this button pressed in this frame?)
Another way is to have some other component continuously call this component every frame, checking these things, raising events to notify of things that are happening (for example -- define an event MouseClicked which will be hooked by the API user).
Why would you favor each of these designs?
Upvotes: 3
Views: 3740
Reputation: 71573
The difference is between a "push" model and a "pull" model, as seen by consuming code. Either works in the context of an input device (at some level, the device is polled by the OS to use as the trigger for an event or simply to set a value that is valid until the next poll). I think the decision to use one or the other is dependent on what is significant; is it clicked now, or has it been clicked? This minor semantic difference can mean major differences in behavior.
If what you are looking for is that a button is pressed as of when you check, then set it up as a polling mechanism. Provide a property that is updated as often as you know how from within your library, that consumers will check in order to determine that a button is being pressed.
If you need to convey that a button was pressed at some time, then set it up as an event, which will "push" this information to its listeners.
Which one you want to use depends on how you structure the program that uses it. A Windows GUI game, where the program is designed from the ground up to simply wait for input, would be best served by an event-based model. A video game, like a side-scroller, where you must know the current state of inputs in order to draw the next frame, might be better served by a polling mechanism.
Quite frankly, in a library like this it would be trivial to set up both scenarios side-by-side; update a property, and then if anyone's listening, shout it out. That way consuming code could push or pull as the user feels necessary for their purpose.
Upvotes: 9
Reputation: 397
May be its better to provide an API where the consumer could specify a callback that could be called with relevant data whenever an event occurs. That way the consumer of your component would not be polling for data.
Upvotes: 1