Another two examples of using changing classes

Terry Reedy tjreedy at home.com
Tue Aug 14 05:34:06 CEST 2001


"Itamar Shtull-Trauring" <itamarst at yahoo.com> wrote in message
news:637b94bc.0108131426.48c84b3d at posting.google.com...
> Changing classes at runtime can be useful at times, and I've done it
> myself at times. And since Twisted uses it and I intend to use
Twisted
> for my server architecture, that's a 3rd use as well.
>
>
> == 1 ==
> I have a proxy class that forwards network requests to a remote
> server. When it gets disconnected, it still needs to respond to
> commands, albeit with failure responses.
>
> However, if a certains commands are given to the instance it can
> reconnect and start working normally again.
>
> The other way to do this is to have two classes - Connected and
> Disconnected, and the instance switches between the classes to
change
> the way it works. Doing this without changing classes would require
> having a frontend instance and a changing backend instance, and
double
> the number of function calls done with every operation.

A third way is to have a 'connected' variable and make every function
conditional on the state variable.  Changing class is much cleaner.

An analogous use in games is when characters get killed and hang
around until resurrection or dissapation of the corpse.

> == 2 ==
> Consider a (SocketServer) network server that supports multiple
> protocols on the same port. When a connection is opened the first
> message tells the handler what protocol to use, and the handler then
> changes its class to the appropriate handler class.

In many games, players start as generic players before
selection/earning a profession/class which adds additional behaviours.
Sometimes there is a second transition to a specialty.This is
naturally modeled as a class hierarchy with transitions implemented by
a class change.

Nice examples.

Terry J. Reedy






More information about the Python-list mailing list