TclOO中借用其他类特定方法的更优雅实现方式咨询
TclOO复用其他类特定方法的优雅方案
1. 原生委托(Delegation)
TclOO本身支持delegate命令,能直接把目标方法委托给其他类的实例或类本身,完全不用复制代码:
oo::class create MyClass { # 把targetMethod委托给OtherClass的实例 delegate method targetMethod to otherInstance constructor {} { set otherInstance [OtherClass new] } }
如果是复用类方法,直接委托给类名就行:
oo::class create MyClass { delegate method classMethod to OtherClass }
2. 混入类(Mixins)
要是需要复用多个方法,或者想让当前类直接拥有其他类的方法实现,用mixins特性最合适,把目标类作为混入类,当前类会自动继承其所有方法:
oo::class create OtherClass { method targetMethod {} { puts "来自OtherClass的方法实现" } } oo::class create MyClass { mixin OtherClass }
3. 直接调用目标方法
如果只是偶尔调用其他类的方法,没必要把方法“搬”过来,直接通过实例或类名调用就行。比如在当前类方法里封装调用:
oo::class create MyClass { method myMethod {} { set otherObj [OtherClass new] $otherObj targetMethod # 直接调用 $otherObj destroy } }
4. 用forward转发方法
forward比委托更灵活,能自定义转发的参数逻辑,把当前类的方法请求转发给其他对象:
oo::class create MyClass { constructor {} { set otherObj [OtherClass new] # 把当前类的targetMethod转发给otherObj的同名方法 forward targetMethod $otherObj targetMethod # 也可以加额外参数:forward targetMethod $otherObj targetMethod "固定参数" } }
之前用info class definition复制代码的方式,不仅会产生冗余代码,后续原方法更新时还得同步复制,上面这些方案都能避免这些问题,既保持复用性,又提升代码维护性。
内容的提问来源于stack exchange,提问作者georgtree
相关产品推荐
相关产品推荐

