Friday 15 February 2013

oop - TclOO: Access nested objects -



oop - TclOO: Access nested objects -

lets presume have 2 classes follows:

oo::class create insidething { constructor {} { puts "made [self] insidething" } destructor { puts "deleted [self] insidething" } method echo {text} { puts "[self]: $text" } } oo::class create container { constructor {} { puts "created [self] container" insidething create inner1 insidething create inner2 } destructor { puts "deleted [self] container" } method echo1 {text} { # how this: $inner1 echo $text } }

how go accessing inner objects? want following:

set c [container new] # (1) accessing inner1 indirectly $c echo1 "hallo world" # (2) accessing inner1 dirctly $c inner1 echo "hallo world"

is there way that? approache create sense?

what want accomplish nested object construction (essentially tree-like). i'd able navigate construction calling methods (e.g. parent, child) on nodes. destroying root should destroy children (thats why used create create nested objects within parent namespace)

to plain utilize contained object, utilize local name, should know because created in constructor. doesn't need held in variable; it's exclusively trivial ensure unique name because in unique namespace (the instance namespace; every tcloo object has own private namespace sort of thing) , command completely.

exposing inner object done using forwarding methods. tcloo comes 2 main sorts of user-configurable methods: “normal” proc-like methods declare method, , forwarding methods (a bit interp alias) declare forward. thing forwards resolved respect instance namespace, ultra-useful! in particular, can create forward method on container class forwards relevant inner object. (insidething unchanged):

oo::class create container { constructor {} { puts "created [self] container" insidething create innerabc insidething create innerdef } destructor { puts "deleted [self] container" } method echo1 {text} { # utilize name. that's all. innerabc echo $text } forwards inner1 innerabc forwards inner2 innerdef }

then can phone call inner object like:

$c inner1 echo "yo!"

or can utilize intermediating normal method this:

$c echo1 "hiya!"

it's you. (the forwarded version around 20% faster in informal testing modified version of code trivial do-nothing echo method implementation. however, real code notice difference less; microbenchmarking useful in reality.)

oop tcl

No comments:

Post a Comment