?? u_command.java
字號:
/*
COMMAND—俺有一個MM家里管得特別嚴,沒法見面,只好借助于她弟弟在我們倆之間傳送信息,她對我有什么指示,就寫一張紙條讓她弟弟帶給我。這不,她弟弟又傳送過來一個COMMAND,為了感謝他,我請他吃了碗雜醬面,哪知道他說:“我同時給我姐姐三個男朋友送COMMAND,就數你最小氣,才請我吃面。”,
命令模式:命令模式把一個請求或者操作封裝到一個對象中。命令模式把發出命令的責任和執行命令的責任分割開,委派給不同的對象。命令模式允許請求的一方和發送的一方獨立開來,使得請求的一方不必知道接收請求的一方的接口,更不必知道請求是怎么被接收,以及操作是否執行,何時被執行以及是怎么被執行的。系統支持命令的撤消。
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class U_Command 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 U_Command(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();
setVisible(true);
}
// ActionListener用
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clearButton) {
history.clear();
canvas.repaint();
}
}
// MouseMotionListener用
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Command cmd = new DrawCommand(canvas, e.getPoint());
history.append(cmd);
cmd.execute();
}
// WindowListener用
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public static void main(String[] args) {
new U_Command("Command Pattern Sample");
}
}
interface Command {
public abstract void execute();
}
class MacroCommand implements Command {
// 命令的集合
private Stack commands = new Stack();
// 執行
public void execute() {
Iterator it = commands.iterator();
while (it.hasNext()) {
((Command)it.next()).execute();
}
}
// 新增
public void append(Command cmd) {
if (cmd != this) {
commands.push(cmd);
}
}
// 刪除最后一個命令
public void undo() {
if (!commands.empty()) {
commands.pop();
}
}
// 全部刪除
public void clear() {
commands.clear();
}
}
interface Drawable {
public abstract void draw(int x, int y);
}
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;
}
// 再度繪制整個記錄
public void paint(Graphics g) {
history.execute();
}
// 繪制
public void draw(int x, int y) {
Graphics g = getGraphics();
g.setColor(color);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
class DrawCommand implements Command {
// 繪制對象
protected Drawable drawable;
// 繪制位置
private Point position;
// 構造子
public DrawCommand(Drawable drawable, Point position) {
this.drawable = drawable;
this.position = position;
}
// 執行
public void execute() {
drawable.draw(position.x, position.y);
}
}
/*
Command定義
n 將來自客戶端的請求傳入一個對象,無需了解這個請求激活的 動作或有關接受這個請求的處理細節。
這是一種兩臺機器之間通訊聯系性質的模式,類似傳統過程語 言的 CallBack功能。
優點:
解耦了發送者和接受者之間聯系。 發送者調用一個操作,接受者接受請求執行相應的動作,因為使用Command模式解耦,發送者無需知道接受者任何接口。
不少Command模式的代碼都是針對圖形界面的,它實際就是菜單命令,我們在一個下拉菜單選擇一個命令時,然后會執行一些動作.
將這些命令封裝成在一個類中,然后用戶(調用者)再對這個類進行操作,這就是Command模式,換句話說,本來用戶(調用者)是直接調用這些命令的,如菜單上打開文檔(調用者),就直接指向打開文檔的代碼,使用Command模式,就是在這兩者之間增加一個中間者,將這種直接關系拗斷,同時兩者之間都隔離,基本沒有關系了.
顯然這樣做的好處是符合封裝的特性,降低耦合度,Command是將對行為進行封裝的典型模式,Factory是將創建進行封裝的模式,
從Command模式,我也發現設計模式一個"通病":好象喜歡將簡單的問題復雜化, 喜歡在不同類中增加第三者,當然這樣做有利于代碼的健壯性 可維護性 還有復用性.
如何使用?
具體的Command模式代碼各式各樣,因為如何封裝命令,不同系統,有不同的做法.下面事例是將命令封裝在一個Collection的List中,任何對象一旦加入List中,實際上裝入了一個封閉的黑盒中,對象的特性消失了,只有取出時,才有可能模糊的分辨出:
典型的Command模式需要有一個接口.接口中有一個統一的方法,這就是"將命令/請求封裝為對象":
public interface Command {
public abstract void execute ( );
}
具體不同命令/請求代碼是實現接口Command,下面有三個具體命令
public class Engineer implements Command {
public void execute( ) {
//do Engineer's command
}
}
public class Programmer implements Command {
public void execute( ) {
//do programmer's command
}
}
public class Politician implements Command {
public void execute( ) {
//do Politician's command
}
}
按照通常做法,我們就可以直接調用這三個Command,但是使用Command模式,我們要將他們封裝起來,扔到黑盒子List里去:
public class producer{
public static List produceRequests() {
List queue = new ArrayList();
queue.add( new DomesticEngineer() );
queue.add( new Politician() );
queue.add( new Programmer() );
return queue;
}
}
這三個命令進入List中后,已經失去了其外表特征,以后再取出,也可能無法分辨出誰是Engineer 誰是Programmer了,看下面客戶端如何調用Command模式:
public class TestCommand {
public static void main(String[] args) {
List queue = Producer.produceRequests();
for (Iterator it = queue.iterator(); it.hasNext(); )
//客戶端直接調用execute方法,無需知道被調用者的其它更多類的方法名。
((Command)it.next()).execute();
}
}
由此可見,調用者基本只和接口打交道,不合具體實現交互,這也體現了一個原則,面向接口編程,這樣,以后增加第四個具體命令時,就不必修改調用者TestCommand中的代碼了.
理解了上面的代碼的核心原理,在使用中,就應該各人有自己方法了,特別是在如何分離調用者和具體命令上,有很多實現方法,上面的代碼是使用"從List過一遍"的做法.這種做法只是為了演示.
使用Command模式的一個好理由還因為它能實現Undo功能.每個具體命令都可以記住它剛剛執行的動作,并且在需要時恢復.
Command模式在界面設計中應用廣泛.Java的Swing中菜單命令都是使用Command模式
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -