命令模式例子------创世纪系统
系统开始时,世界是个黑暗的窗体,窗体上有4个按钮: Let There Be Light(要有光), Let There Be Land(要有地),Reset(复原),God Rests(上帝休息了)
代码:
/* 抽象命令角色 */
public interface CommandFromGod
{
public void Execute();
}
import java.awt.*;
import java.awt.event.*;
/* 具体命令角色,Let There be light*/
public class LetThereBeLightCommand extends Button implements CommandFromGod
{
Panel p;
public LetThereBeLightCommand(String caption, Panel pnl)
{
super(caption);
p = pnl;
}
public void Execute()
{
p.setBackground(Color.white);
}
}
import java.awt.*;
import java.awt.event.*;
/* 具体命令角色,Let There be land*/
public class LetThereBeLandCommand extends Button implements CommandFromGod
{
Panel p;
public LetThereBeLandCommand(String caption, Panel pnl)
{
super(caption);
p = pnl;
}
public void Execute()
{
p.setBackground(Color.orange);
}
}
import java.awt.*;
import java.awt.event.*;
/* 具体命令角色,Rests*/
public class GodRestsCommand extends Button implements CommandFromGod
{
public GodRestsCommand(String caption)
{
super(caption);
}
public void Execute()
{
System.exit(0);
}
}
import java.awt.*;
import java.awt.event.*;
/* 具体命令角色,Reset*/
public class ResetCommand extends Button implements CommandFromGod
{
Panel p;
public ResetCommand(String caption, Panel pnl)
{
super(caption);
p = pnl;
}
public void Execute()
{
p.setBackground(Color.black);
}
}
import java.awt.*;
import java.awt.event.*;
/* Client */
public class TheWorld extends Frame implements ActionListener
{
LetThereBeLightCommand btnLight;
LetThereBeLandCommand btnLand;
ResetCommand btnReset;
GodRestsCommand btnExit;
Panel p;
public TheWorld()
{
super("This is the world, and God says...");
p = new Panel();
p.setBackground(Color.black);
add(p);
btnLight = new LetThereBeLightCommand("Let there be light", p);
btnLand = new LetThereBeLandCommand("Let there be land", p);
btnReset = new ResetCommand("Reset", p);
btnExit = new GodRestsCommand("God rests");
p.add(btnLight);
p.add(btnLand);
p.add(btnReset);
p.add(btnExit);
btnLight.addActionListener(this);
btnLand.addActionListener(this);
btnReset.addActionListener(this);
btnExit.addActionListener(this);
setBounds(100,100,400,200);
setVisible(true);
}
//-----------------------------------------
public void actionPerformed(ActionEvent e)
{
CommandFromGod obj = (CommandFromGod)e.getSource();
obj.Execute();
}
//-----------------------------------------
static public void main(String[] argv)
{
new TheWorld();
}
}
这个例子中没有Recevier角色和Invoker角色,此处完全可以分离出这两种角色,这样的话似乎更复杂了!