Tcl8.6原生支持oop了
时间:2010-09-18 来源:阿尔法蕾特
虽然tcl早先的版本就已经有oop的支持(itcl、XOTcl等),但是都是以外部扩展库的模式出现。因为习惯使用稳定版本,所以一直用tcl 8.5。前段时间安装了Mandriva 2010 sprint默认安装了tcl 8.6,于是下了相关文档浏览一下,发现Tcl Commands里面多了oo::class, oo::copy, oo::define, oo::objdefine, oo::object几条命令。由于时间比较晚,粗略看了下相关描述,让我比较惊奇的是tcl 8.6貌似同时支持两种类模型:基于类和基于原型,分别对应oo::class与oo::object,oo::class是经典的类模型,先上一段代码:
oo::class create fruit {
method eat {} {
puts "yummy!"
}
}
oo::class create banana {
superclass fruit
constructor {} {
my variable peeled
set peeled 0
}
method peel {} {
my variable peeled
set peeled 1
puts "skin now off"
}
method edible? {} {
my variable peeled
return $peeled
}
method eat {} {
if {![my edible?]} {
my peel
}
next
}
}
set b [banana new]
$b eat → prints "skin now off" and "yummy!"
上面的代码可以很直观看出oo::class是经典的基类继承模型,而oo::object则是:
set obj [oo::object new]
$obj foo → error "unknown method foo"
oo::objdefine $obj method foo {} {
my variable count
puts "bar[incr count]"
}
$obj foo → prints "bar1"
$obj foo → prints "bar2"
这则代码中的方法是在对象创建后才动态添加的,很明显oo::object所创建出来的是metaclass,oo::class的描述也印证了我这个想法:
The oo::class class is the class of all classes; every class is aninstance of this class, which is consequently an instance of itself. Thisclass is a subclass of oo::object, so every class is also an object.Additional metaclasses (i.e. classes of classes) can be defined if necessaryby subclassing oo::class. Note that the oo::class object hides thenew method on itself, so new classes should always be made using thecreate method.
Thisclass is a subclass of oo::object, so every class is also an object.Additional metaclasses 很清楚地说明了任何用oo::class创建的类都是oo::object的子类,因此oo::classs实际就是oo::object的一种上层封装(基于原型的类模型比经典类模型具有更大自由度及灵活性),由此大体可以看出tcl 8.6的原生类模型是一种基于原型的类模型。
时间较晚,研究得比较粗浅,大家就先凑合着看看当是开胃小菜吧....