求一个Command设计模式的程序例子以理解Command模式,例子越短越简单越好

Patrick_DK 2002-03-12 06:54:44
如题
...全文
137 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Patrick_DK 2002-03-13
  • 打赏
  • 举报
回复
初级例子
----------------------------------
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class CommandPattern2
{
public static void main(String[] args)
{
JFrame jFrame=new JFrame("Command Pattern");

ExitJButton exitJButton=new ExitJButton("Exit");
PrintJButton printJButton=new PrintJButton("Print");
RunJButton runJButton=new RunJButton("Run");

CustomListener cl=new CustomListener();

exitJButton.addActionListener(cl);
printJButton.addActionListener(cl);
runJButton.addActionListener(cl);

jFrame.getContentPane().setLayout(new FlowLayout());
jFrame.getContentPane().add(exitJButton);
jFrame.getContentPane().add(printJButton);
jFrame.getContentPane().add(runJButton);

jFrame.setBounds(200,200,400,400);
jFrame.setVisible(true);
}
}


abstract interface Command
{
public abstract void execute();
}


class ExitJButton extends JButton implements Command
{
public ExitJButton(String label)
{
super(label);
}

public void execute()
{
System.out.println("exit event");
}
}


class PrintJButton extends JButton implements Command
{
public PrintJButton(String label)
{
super(label);
}

public void execute()
{
System.out.println("print event");
}
}


class RunJButton extends JButton implements Command
{
public RunJButton(String label)
{
super(label);
}

public void execute()
{
System.out.println("run event");
}
}


class CustomListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
Command cmd=(Command)ae.getSource();
cmd.execute();
}
}
aprim 2002-03-12
  • 打赏
  • 举报
回复
上面的代码都在exeute()中直接实现了,也可把操作提出到一个指定的CommandReceiver类中,实现真正的 发送者(sender)和接收者(receiver)完全解耦(decoupling)。。。
Patrick_DK 2002-03-12
  • 打赏
  • 举报
回复
to 楼上:

你说的四人帮那本是不是那本最有名的《设计模式》啊?

Design Pattern(Java版)我有,不过是英文的,主要内容太抽象了,可能不好懂,而且评价不是很高啊

你看过吗,能具体说说吗?
zhengqingshan 2002-03-12
  • 打赏
  • 举报
回复
这是我的理解:
public interface command{
public void execute()
}
比如你的程序有若干按钮:可能响应他们的actionperformed如下:
public void actionPerformed(ActionEvent e)
{object o=e.getSource()
if (o==bnt1) fileOpen();//关闭文件
if (o==bnt2) fileClose();
.....
这样的话,会暴露每个按钮各自的内部信息(比如,他们是用来干什么的),而且一堆判断语句也不好,如果这样:
public class closeButton extends JButton implements command{
public void execute(){
System.exit(0);
}
.............
把每一个按钮要干什么,写在他自己的类里
然后
closeButton b=new closeButton();
b.addActionListener(new listener());

public class listener implements actionListener{
public void actionPerformed(actionEvent e){
command o=(command)e.getSource();
o.exeute();/////这样,以后每一个实现了command接口的对象都可用这 //监听者,而且也不用知道关于事件的具体信息 // 比如是哪一个对象引发,从而决定具体要干什么
可以简化代码(只不过要多写几个实现command接口的类
}

建议看看design pattern(java版),例子简单,比四人帮那本容易理解的多

23,409

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧