Posted to tcl by aspect at Wed Sep 10 15:02:35 GMT 2014view raw

  1. # a klass is a place for defining additional "class definition" methods, in addition
  2. # to those normally available via oo::define.
  3. oo::class create klass {
  4. superclass oo::class
  5. constructor {Script} {
  6. oo::define [self] superclass [self class] ;# every klass is a subclass of klass. hm.
  7.  
  8. set myns [self namespace] ;# create a namespace that wraps ::oo::define
  9. ;# and will be extended with our methods
  10. foreach cmd [map {namespace tail} [info commands ::oo::define::*]] {
  11. if {$cmd ne "self"} {
  12. interp alias {} ${myns}::$cmd {} ::oo::define [self] $cmd
  13. }
  14. }
  15. foreach cmd [info object methods [self] -all] {
  16. if {$cmd ni {new create destroy}} {
  17. interp alias {} ${myns}::$cmd {} [self] $cmd
  18. }
  19. }
  20. try $Script ;# instead of [next]
  21. }
  22. }
  23.  
  24. # AbstractBase is a klass which provides "abstractmethod"
  25. klass create AbstractBase {
  26. variable abstractmethods
  27. constructor args {
  28. set abstractmethods {}
  29. next {*}$args
  30. oo::define [self] constructor {args} [format {
  31. debug log {Constructing an abstract instance [self] that needs %1$s}
  32. next {*}$args
  33. set mymethods [info class methods [self] -all]
  34. foreach m %1$s {
  35. if {$m ni $mymethods} {
  36. throw {CLASS ABSTRACTMETHOD} "abstract method $m not provided in [self]!"
  37. }
  38. }
  39. } [list $abstractmethods]]
  40. }
  41. method abstractmethod {name} {
  42. lappend abstractmethods $name
  43. }
  44. }
  45.  
  46. # now attempt to use it
  47. AbstractBase create Channish {
  48. abstractmethod read
  49. abstractmethod write
  50. # method, constructor, etc
  51. }
  52.  
  53. Channish create Try {
  54. method read {args} {}
  55. method write {} {}
  56. }
  57.  
  58. Channish create Try2 {
  59. method read {args} {}
  60. } ;# error!
  61.  
  62. ;# the three (?) inheritance hierarchies in play here confuse the heck out of me
  63.  
  64.