抽象类windowadapter是变压器模式的一个例子
抽象类windowadapter是为接受视窗的事件而准备的。此抽象类内所有的方法都是空的。 使用此类可以很方便地创立listener对象。置换(override)你所感兴趣的那个事件所对应的方法。 如果你不使用此抽象类,那么你必然规律要实现windowslistener接口,而那样你就不得不实现所有接口中的方法, 即便是你不需要的事件所对应的方法,你也要给出一个空的方法,而这显然不方便。
显然,抽象类windowadapter的目标接口可以选得与源接口一样,而不影响效果。 这就解释了为什么目标接口不出现在windowadapter类图(见下面)里。
swingui类的代码如下。
import java.awt.color;
import java.awt.borderlayout;
import java.awt.event.*;
import javax.swing.*;
class swingui extends jframe implements actionlistener
{
jlabel text, clicked;
jbutton button, clickbutton;
jpanel panel;
private boolean m_clickmemode = true;
public swingui()
{
text = new jlabel("我很高兴!");
button = new jbutton("理我");
button.addactionlistener(this);
panel = new jpanel();
panel.setlayout(new borderlayout());
panel.setbackground(color.white);
getcontentpane().add(panel);
panel.add(borderlayout.center, text);
panel.add(borderlayout.south, button);
}
public void actionperformed(actionevent event)
{
object source = event.getsource();
if (m_clickmemode)
{
text.settext("我很烦!");
button.settext("别理我");
m_clickmemode = false;
}
else
{
text.settext("我很高兴!");
button.settext("理我");
m_clickmemode = true;
}
}
public static void main(string[] args)
{
swingui frame = new swingui();
frame.settitle("我");
windowlistener listener = new windowadapter()
{
public void windowclosing(windowevent e)
{
system.exit(0);
}
};
frame.addwindowlistener(listener);
frame.pack();
frame.setvisible(true);
}
}
public class cube
{
public cube(double width)
{
this.width = width;
}
public double calculatevolume()
{
return width * width * width;
}
public double calculatefacearea()
{
return width * width;
}
public double getwidth()
{
return this.width;
}
public void setwidth(double width)
{
this.width = width;
}
private double width;
}
package com.javapatterns.adapter.cube2ball;
public interface ballif
{
double calculatearea();
double calculatevolume();
double getradius();
void setradius(double radius);
}
package com.javapatterns.adapter.cube2ball;
public class magicfinger implements ballif
{
public magicfinger(cube adaptee)
{
super();
this.adaptee = adaptee;
radius = adaptee.getwidth();
}
public double calculatearea()
{
return pi * 4.0d * ( radius * radius );
}
public double calculatevolume()
{
return pi * 4.0d/3.0d * ( radius * radius * radius );
}
public double getradius()
{
return radius;
}
public void setradius(double radius)
{
this.radius = radius;
}
private double radius = 0;
private static final double pi = 3.14d;
private cube adaptee;
}
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器