Richard Suchenwirth 2007-10-20 - Now that I have TclOO both at work and home, and another weekend comes up, it's obvious that I wanted to play with it, just for finger practice. Barking dogs have been demonstrated elsewhere, but I decided to start with another classic example, a bank account.
#!/usr/bin/env tclsh85 package require TclOO namespace import oo::* catch {Account destroy} ;# in case of repeated sourcing class create Account { constructor {{ownerName undisclosed}} { my variable total overdrawLimit owner set total 0 set overdrawLimit 10 set owner $ownerName } method deposit amount { my variable total set total [expr {$total + $amount}] } method withdraw amount { my variable {*}[info object vars [self]] if {($amount - $total) > $overdrawLimit} { error "Can't overdraw - total: $total, limit: $overdrawLimit" } set total [expr {$total - $amount}] } method transfer {amount targetAccount} { my variable total my withdraw $amount $targetAccount deposit $amount set total } }
if 0 {Due to the simple hierarchy of TclOO (every class is an instance of oo::class, which is an instance of oo::object), it is not very hard to add development helper methods that each object inherits:}
define oo::object method dump {{pat *}} { set res [list class [info object class [self]]] foreach i [info object vars [self] $pat] { my variable $i lappend res $i [set $i] } set res }
#-- "Test suite"
foreach cmd [split { set a [Account new "John Doe"] $a deposit 200 $a deposit 20 $a withdraw 150 $a withdraw 100 $a dump set b [Account new] $a transfer 65 $b $a dump $b dump $a transfer 1000000 $b } \n] { catch $cmd res puts "$cmd -> $res" }
if 0 {which prints
set a [Account new "John Doe"] -> ::oo::Obj36 $a deposit 200 -> 200 $a deposit 20 -> 220 $a withdraw 150 -> 70 $a withdraw 100 -> Can't overdraw - total: 70, limit: 10 $a dump -> class ::Account total 70 overdrawLimit 10 owner {John Doe} set b [Account new] -> ::oo::Obj37 $a transfer 65 $b -> 5 $a dump -> class ::Account total 5 overdrawLimit 10 owner {John Doe} $b dump -> class ::Account total 65 overdrawLimit 10 owner undisclosed $a transfer 1000000 $b -> Can't overdraw - total: 5, limit: 10
}
Category Example | Category Object orientation |