Groovy探索之Delegate模式 一
Delegate即是委派的意思。在Java语言中,很少提到委派或者委派模式,即使用到了也不说,这是因为Java语言的特点,实现起委派来相当的繁琐,而且只能适用于一些简单的场合。
但现实的需求是,由于敏捷编程的兴起,重构技术也得到了大家的广泛使用;要使用重构,其中的一个重要原则是:使用组合代替聚合,这样才能方便重构。使用组合,最终是要使用到委派技术了。同时,我们经常有这样的一些需求,我们只想继承一个类的部分功能,而另外一部分功能是我们不想要、甚至是对我们有害的功能,这时候,我们只能使用委派技术,而不能使用继承了。
说了这么多,您可能要说了,我想看一些例子,或者你举出一些例子来证明你的观点啊。这正是下面要做的事。
比方说,有下面的一个简单类:
class
Foo {
def
test
()
{
println
'have a test'
}
def
foo()
{
println
'foo...'
}
}
class
FooSon
extends
Foo{
def
testAgain()
{
println
'test it again'
}
}
def
foo =
new
FooSon()
foo.
test
()
foo.foo()
foo.testAgain()
它的运行结果为:
have a test
foo...
test it again
如果您的答案是否定的,请您跟着我往下看。
class
Foo2 {
private
delegate =
new
Foo()
def
test
()
{
this
.delegate.
test
()
}
def
foo()
{
this
.delegate.foo()
}
def
testAgain()
{
println
'test it again'
}
}
通过这个例子,您可以看到,所谓“委派”的意思是:一个类要实现的功能,比如
Foo2
类要实现的“
test
”和“
foo
”方法,但它并未真正去实现这些功能,而是把这些功能委派给另一个类去实现,如
Foo2
类的“
test
”和“
foo
”方法,实际上是交给
Foo
类去实现了。
可以测试一下上面的例子:
def
foo =
new
Foo2()
foo.
test
()
foo.foo()
foo.testAgain()
运行结果为:
have a test
foo...
test it again
class
Foo2 {
private
delegate =
new
Foo()
def
test
()
{
this
.delegate.
test
()
}
def
testAgain()
{
println
'test it again'
}
}
看了上面的例子,您可能会说,委派技术很简单,也很好理解,但就是实现起来太繁琐了,我要想在子类中实现父类的方法,非得在子类中把这些方法重写一遍不可,远远没有继承来得方便。是的,这就是在Java语言中很少提到委派技术的原因。
但是,我们应该知道的是,Groovy语言是基于Java语言的,这使得它必定有超过Java语言之处,而对委派技术的动态实现正是Groovy语言动态的一个重要方面。下面,我将举出一个例子来实现上面的功能的动态委派技术。
class
Foo3 {
private
delegate =
new
Foo()
def
invokeMethod(String name,Object args)
{
this
.delegate.invokeMethod(name,args)
}
def
testAgain()
{
println
'test it again'
}
}
def
foo =
new
Foo3()
foo.
test
()
foo.foo()
foo.testAgain()
结果为:
have a test
foo...
test it again
class
Foo3 {
private
delegate =
new
Foo()
def
invokeMethod(String name,Object args)
{
if
(name !=
'foo'
)
{
this
.delegate.invokeMethod(name,args)
}
}
def
testAgain()
{
println
'test it again'
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。