命令模式--撤销恢复
该例子来自阎宏提供的例子程序,以画线为例:
?命令接口Command:
/* Generated by Together */package com.javapatterns.command.drawlines;import java.applet.Applet;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Panel;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;// 请求者(负责调用命令对象执行请求)public class SimpleDraw extends Applet implements ActionListener {private static final long serialVersionUID = 2317696438230972428L;private Drawing drawing;// 画布private CommandList commands;// 命令集合private Button undoButton;// 撤销按钮private Button redoButton;// 恢复按钮private Button resetButton;// 清空撤销和恢复按钮public void init() {Panel panel = new Panel();// 面板commands = new CommandList();// 初始化命令集合setLayout(new BorderLayout());// 设置布局drawing = new Drawing(this);// 初始化画布add("Center", drawing);undoButton = new Button("撤销");// 初始化撤销按钮redoButton = new Button("恢复");// 初始化恢复按钮resetButton = new Button("重置");undoButton.addActionListener(this);// 添加按钮监听器redoButton.addActionListener(this);// 添加按钮监听器resetButton.addActionListener(this);// 添加按钮监听器panel.add(undoButton);panel.add(redoButton);panel.add(resetButton);add("South", panel);updateButtons();// 初始化按钮状态}public void execute(Command command) {commands.execute(command);// 执行命令updateButtons();}// 更新按钮状态(根据是否能够undo撤销或者是否能够redo恢复)private void updateButtons() {undoButton.setEnabled(commands.canUnexecuteCommand());redoButton.setEnabled(commands.canReexecuteCommand());}// 当点击撤销按钮或者恢复按钮时出发该方法执行public void actionPerformed(ActionEvent event) {if (event.getSource() == undoButton) {commands.unexecute();updateButtons();}else if (event.getSource() == redoButton) {commands.reexecute();updateButtons();}else if (event.getSource() == resetButton) {commands.reset();updateButtons();}}}
?
1 楼 snowdream 2011-11-25 写的很不错,感谢分享。