Groovy探索之Adapater模式
有这么一个灯的类:
class
Light {
def
turnOn()
{
println
'The light is on,you can do anything……'
}
def
turnOff()
{
println
'Be careful!the light is power off……'
}
}
现在的需要是,我们要创建一个Button类,希望它既能控制Light类对象的开关。同时,也可以控制其他类,如我们自己创建的风扇类(Fan),冰箱类,电视机类等等的开关。
这个思路是对的,但现在的难题是我们不能修改Light类,使它实现我们的接口。怎么办?这时候,我们的Adapter模式就派上用场了。
public interface Switch
{
public void turnOn();
public void turnOff();
}
public class LightAdapter implements Switch
{
private Light light = new Light();
public void turnOn()
{
light.turnOn();
}
public void turnOff()
{
light.turnOff();
}
}
最后来实现Button类:
public class Button
{
private Switch switch;
public Button(Switch switch)
{
this.switch = switch;
}
public void pressOn()
{
this.switch.trunOn();
}
public void pressOff()
{
this.switch.turnOff();
}
}
这样,我们的Button类通过控制
LightAdapter
类间接控制了
Light
类,而其他的风扇类、空调类等等,只是它们实现了
Switch
接口,就都能被
Button
类控制。
通过上面的代码,我们可以看到,本例对于
Adapter
模式的使用是通过两个委派动作来完成的。即
LightAdapter
类把动作委派给
Light
类,而
Button
类又把动作委派给
LightAdapter
类等各类。
我们知道,
Java
语言受语言的限制,对委派的使用很低级。我们可以这么说,正是由于
Java
语言不能很好的使用委派,才导致了实现
Adapter
模式的难度。
闲话少说,我们来看看
Groovy
语言是如何实现上述的
Adapter
模式的:
class
Button {
def
delegate
def
Button(delegate)
{
this
.delegate = delegate
}
def
turnOn()
{
try
{
this
.delegate.turnOn()
}
catch
(MissingMethodException e)
{
println
"Your class: ${this.delegate.class.name} need to implement turnOn and turnOff function!"
}
}
def
turnOff()
{
try
{
this
.delegate.turnOff()
}
catch
(MissingMethodException e)
{
println
"Your class: ${this.delegate.class.name} need to implement turnOn and turnOff function!"
}
}
}
可以看到,在
Groovy
语言中,实现上述的
Adapter
模式根本不需要
Switch
接口,也不需要
LightAdapter
类,直接在
Button
类里把功能委派给各个类对象就行了。当然,我们能在
Groovy
语言中实现这样的委派,是由
Groovy
语言的动态性决定的。
现在,我们来测试一下
Groovy
语言的
Button
类:
def
button =
new
Button(
new
Light())
button.turnOn()
button.turnOff()
运行结果为:
The light is on,you can do anything……
Be careful!the light is power off……
def
button =
new
Button(
new
Fan())
button.turnOn()
运行结果为:
Your class: Fan need to implement turnOn and turnOff function!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。