java内的命令(Command)模式例子

命令模式例子------创世纪系统

 

系统开始时,世界是个黑暗的窗体,窗体上有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角色,此处完全可以分离出这两种角色,这样的话似乎更复杂了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值