当前页面: 开发资料首页 → Java 专题 → java结构性模式之变压器模式介绍(三)
摘要: java结构性模式之变压器模式介绍(三)
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;
}