Another two examples of using changing classes
tomh at optiscan.com
Tue Aug 14 09:02:56 CEST 2001
Fascinating, Captain .
Coming from a C++ background I did this in Python by a class having a member
instance of a proxy class that was changed to according to what it was
talking to (like example 2). Pattern junkies refer to this as the State
pattern, the Patterns Book defines it as "Allow an object to alter its
behaviour when its internal state changes. The object will appear to change
its state.". In Python I can now see how to code this by the class _really_
changing its class at runtime. The involved example in the Patterns book on
the implementation of the State pattern becomes a few lines in Python.
This is similar to the Python implementation of the Factory pattern which
collapses it to a single line. Should Python be known as "The language where
Patterns become Idioms?"
Tom Harris, Software Engineer
Optiscan Imaging, 15-17 Normanby Rd, Notting Hill, Melbourne, Vic 3168,
email tomh at optiscan.com ph +61 3 9538 3333 fax +61 3 9562 7742
This email may contain confidential information. If you have received this
email in error, please delete it immediately,and inform us of the mistake by
return email. Any form of reproduction, or further dissemination of this
email is strictly prohibited.
Also, please note that opinions expressed in this email are those of the
author, and are not necessarily those of OptiScan Pty Ltd
> -----Original Message-----
> From: itamarst at yahoo.com [SMTP:itamarst at yahoo.com]
> Sent: Tuesday, 14 August 2001 8:26
> To: python-list at python.org
> Subject: Another two examples of using changing classes
> 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.
> == 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.
More information about the Python-list