States Using Function Objects

In languages like Java or Smalltalk, function objects are easy to create. You can use them to encode stateful behavior. This is a variant on ObjectsForState? [StatePattern ?]. -- AamodSane


Suppose you have file browser with a "More" button. When it comes up, it shows only "html" files. Next time it shows ".img" files as well. Finally, it goes deeper down the directory tree. (Yes, its a bit contrived :-). One way to program this would be to keep several variables for file types, a "times" variable etc. and use nested ifs to do the right thing. But this can quickly get out of hand.

Instead, keep a list of "whatNext" functions that holds function objects. Functions in the list are invoked one by one, and then it "wraps around". In the above example, whatNext is ShowHTML followed by ShowIMG followed by ShowDirectories?.

Maintaining a list or tree explicitly, with a policy for choosing what next separates out the choice of what to do next from the functions themselves. This can be clearer than using ObjectForState? [StatePattern ?], where the state itself chooses what to do next.


EditText of this page (last edited April 27, 1999) or FindPage with title or text search