原理:
时序图:
代码清单:
command.Command
public interface Command { void execute();}
command.MacroCommand
public class MacroCommand implements Command{ private Stack commands = new Stack(); @Override public void execute() { Iterator it = commands.iterator(); while(it.hasNext()){ ((Command)it.next()).execute(); } } public void append(Command cmd){ if(cmd!=null){ commands.push(cmd); } } public void undo(){ if(!commands.empty()){ commands.pop(); } } public void clear(){ commands.clear(); }}
drawer.Drawable
public interface Drawable { void draw(int x,int y);}
drawer.DrawCanvas
public class DrawCanvas extends Canvas implements Drawable{ //颜色 private Color color = Color.red; //要绘制元的半径 private int radius = 6; //命令历史记录 private MacroCommand history; public DrawCanvas(int width,int height,MacroCommand history){ setSize(width,height); setBackground(Color.WHITE); this.history = history; } //绘制 @Override public void draw(int x, int y) { Graphics g = getGraphics(); g.setColor(color); g.fillOval(x-radius,y-radius,radius*2,radius*2); } public void point(Graphics g){ history.execute(); }}
drawer.DrawCommand
public class DrawCommand implements Command{ //绘制对象 protected Drawable drawable; //绘制位置 private Point position; public DrawCommand(Drawable drawable, Point position) { this.drawable = drawable; this.position = position; } @Override public void execute() { drawable.draw(position.x,position.y); }}
Main
public class Main extends JFrame implements ActionListener,MouseMotionListener,WindowListener{ //绘制的历史记录 private MacroCommand history = new MacroCommand(); //绘制区域 private DrawCanvas canvas = new DrawCanvas(400,400,history); //删除按钮 private JButton clearButton = new JButton("clear"); public Main(String title){ super(title); this.addWindowListener(this); canvas.addMouseMotionListener(this); clearButton.addActionListener(this); Box buttonBox = new Box(BoxLayout.X_AXIS); buttonBox.add(clearButton); Box mainBox = new Box(BoxLayout.Y_AXIS); mainBox.add(buttonBox); mainBox.add(canvas); getContentPane().add(mainBox); pack(); show(); } public static void main(String[] args){ new Main("命令模式"); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == clearButton){ history.clear(); canvas.repaint(); } } @Override public void mouseDragged(MouseEvent e) { Command cmd = new DrawCommand(canvas,e.getPoint()); history.append(cmd); cmd.execute(); } @Override public void mouseMoved(MouseEvent e) { } @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { System.exit(0); } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { }}