I am looking for real world examples of (open source) programs (or algorithms) that change the concrete class of an object (or variable) at runtime.
An example of such behaviour in Java could look like the code snipper below.
Here, a LinkedList
, which performs well in the context of frequent inserts and/or removes, is changed into an ArrayList
, which performs well in the context of random access and iteration.
List myList = new LinkedList();
/* Lots of inserts */
...
myList = new ArrayList( myList ); // 'change' into different class
/* Lots of iteration */
...
The Java example above changes between LinkedList
and ArrayList
for the
sake of performance.
However, examples in any language, for any data structure, using any technique*, and for any reason are welcome.
*Technique: plain and simple like in the example above, or
using become:
in SmallTalk,or __class__
in Python, or ...
You might want to check use cases for become
method in Smalltalk. The method changes the class of the instance at runtime (or to change all references to the instance to reference different instance)
Become is commonly used to grow/shrink collections, e.g. Dictionary with more buckets, ByteArray with bigger buffer etc. It is possible to convert from SmallInteger to BigIntegers (former are limited in size, latter are not, but are much slower), and the programmer wouldn't even notice (this is reasonable only if you have mutable integers, therefore this is not how this is done in Smalltalk. But it could be :)
Another case might be when loading an instance from serialized form back into the running system, and updating its class to the newest version.
Yes, look at #become in Smalltalk (for instance MIT licensed Pharo.org).
Beside the examples already given #become is for instance usefull when you work with proxies. Think of a proxy object within an ORM framework like Glorp where you first have the proxy and when the real full object is needed it can be loaded from a database and easily all references will be switched.
Another example is the Fuel framework in Pharo.
Don't know if this is relevant but maybe the usage of spy (partial mocks) also fits your description (see http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Spy.html):
An example:
Person person = new Person();
person = spy(person);
doReturn("dominiek").when(person).getName();
Behind the scenes a subclass is created and the behavior of the class is altered according to the users' behavior declarations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With