`
starbhhc
  • 浏览: 649556 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
社区版块
存档分类
最新评论

Command模式2例子

阅读更多
//[C] 2002 Sun Microsystems, Inc.---   
import java.awt.Container;   
import java.awt.event.ActionEvent;   
import java.awt.event.ActionListener;   
import java.awt.event.WindowAdapter;   
import java.awt.event.WindowEvent;   
import java.io.Serializable;   
import java.util.Calendar;   
import java.util.Date;   
  
import javax.swing.BoxLayout;   
import javax.swing.JButton;   
import javax.swing.JFrame;   
import javax.swing.JLabel;   
import javax.swing.JPanel;   
import javax.swing.JTextArea;   
import javax.swing.JTextField;   
  
  
public class RunCommandPattern {   
    private static Calendar dateCreator = Calendar.getInstance();   
       
    public static void main(String [] arguments){   
        System.out.println("Example for the Command pattern");   
        System.out.println();   
        System.out.println("This sample will use a command class called");   
        System.out.println(" ChangeLocationCommand to update the location");   
        System.out.println(" of an Appointment object.");   
        System.out.println("The ChangeLocationCommand has the additional");   
        System.out.println(" ability to undo and redo commands, so it can");   
        System.out.println(" set the locaition back to its original value,");   
        System.out.println(" if desired.");   
        System.out.println();   
           
        System.out.println("Creating an Appointment for use in the demo");   
        Contact [] people = { new ContactImpl(), new ContactImpl() };   
        Appointment appointment = new Appointment("Java Twister Semi-Finals",   
            people, new LocationImpl(""), createDate(2001, 10, 31, 14, 30),   
            createDate(2001, 10, 31, 14, 31));   
           
        System.out.println("Creating the ChangeLocationCommand");   
        ChangeLocationCommand cmd = new ChangeLocationCommand();   
        cmd.setAppointment(appointment);   
           
        System.out.println("Creating the GUI");   
        CommandGui application = new CommandGui(cmd);   
        application.setAppointment(appointment);   
        cmd.setLocationEditor(application);   
        application.createGui();   
           
    }   
    public static Date createDate(int year, int month, int day, int hour, int minute){   
        dateCreator.set(year, month, day, hour, minute);   
        return dateCreator.getTime();   
    }   
}   
class CommandGui implements ActionListener, LocationEditor{   
    private JFrame mainFrame;   
    private JTextArea display;   
    private JTextField updatedLocation;   
    private JButton update, undo, redo, exit;   
    private JPanel controlPanel, displayPanel, editorPanel;   
    private UndoableCommand command;   
    private Appointment appointment;   
       
    public CommandGui(UndoableCommand newCommand){   
        command = newCommand;   
    }   
       
    public void setAppointment(Appointment newAppointment){   
        appointment = newAppointment;   
    }   
       
    public void createGui(){   
        mainFrame = new JFrame("Command Pattern Example");   
        Container content = mainFrame.getContentPane();   
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));   
           
        editorPanel = new JPanel();   
        editorPanel.add(new JLabel("Location"));   
        updatedLocation = new JTextField(20);   
        editorPanel.add(updatedLocation);   
        content.add(editorPanel);   
           
        displayPanel = new JPanel();   
        display = new JTextArea(10, 40);   
        display.setEditable(false);   
        displayPanel.add(display);   
        content.add(displayPanel);   
           
        controlPanel = new JPanel();   
        update = new JButton("Update Location");   
        undo = new JButton("Undo Location");   
        redo = new JButton("Redo Location");   
        exit = new JButton("Exit");   
        controlPanel.add(update);   
        controlPanel.add(undo);   
        controlPanel.add(redo);   
        controlPanel.add(exit);   
        content.add(controlPanel);   
           
        update.addActionListener(this);   
        undo.addActionListener(this);   
        redo.addActionListener(this);   
        exit.addActionListener(this);   
           
        refreshDisplay();   
        mainFrame.addWindowListener(new WindowCloseManager());   
        mainFrame.pack();   
        mainFrame.setVisible(true);   
    }   
       
    public void actionPerformed(ActionEvent evt){   
        Object originator = evt.getSource();   
        if (originator == update){   
            executeCommand();   
        }   
        if (originator == undo){   
            undoCommand();   
        }   
        if (originator == redo){   
            redoCommand();   
        }   
        else if (originator == exit){   
            exitApplication();   
        }   
    }   
       
    private class WindowCloseManager extends WindowAdapter{   
        public void windowClosing(WindowEvent evt){   
            exitApplication();   
        }   
    }   
       
    public Location getNewLocation(){   
        return new LocationImpl(updatedLocation.getText());   
    }   
       
    private void executeCommand(){   
        command.execute();   
        refreshDisplay();   
    }   
       
    private void undoCommand(){   
        command.undo();   
        refreshDisplay();   
    }   
       
    private void redoCommand(){   
        command.redo();   
        refreshDisplay();   
    }   
       
    private void refreshDisplay(){   
        display.setText(appointment.toString());   
    }   
       
    private void exitApplication(){   
        System.exit(0);   
    }   
}   
interface Command{   
    public void execute();   
}   
interface Contact extends Serializable{   
    public static final String SPACE = " ";   
    public String getFirstName();   
    public String getLastName();   
    public String getTitle();   
    public String getOrganization();   
       
    public void setFirstName(String newFirstName);   
    public void setLastName(String newLastName);   
    public void setTitle(String newTitle);   
    public void setOrganization(String newOrganization);   
}   
  
class ContactImpl implements Contact{   
    private String firstName;   
    private String lastName;   
    private String title;   
    private String organization;   
    public static final String EOL_STRING =   
        System.getProperty("line.separator");   
       
    public ContactImpl(){ }   
    public ContactImpl(String newFirstName, String newLastName,   
        String newTitle, String newOrganization){   
            firstName = newFirstName;   
            lastName = newLastName;   
            title = newTitle;   
            organization = newOrganization;   
    }   
       
    public String getFirstName(){ return firstName; }   
    public String getLastName(){ return lastName; }   
    public String getTitle(){ return title; }   
    public String getOrganization(){ return organization; }   
       
    public void setFirstName(String newFirstName){ firstName = newFirstName; }   
    public void setLastName(String newLastName){ lastName = newLastName; }   
    public void setTitle(String newTitle){ title = newTitle; }   
    public void setOrganization(String newOrganization){ organization = newOrganization; }   
       
    public String toString(){   
        return firstName + " " + lastName;   
    }   
}   
  
class Appointment{   
    private String reason;   
    private Contact[] contacts;   
    private Location location;   
    private Date startDate;   
    private Date endDate;   
  
    public Appointment(String reason, Contact[] contacts, Location location, Date startDate, Date endDate){   
        this.reason = reason;   
        this.contacts = contacts;   
        this.location = location;   
        this.startDate = startDate;   
        this.endDate = endDate;   
    }   
       
    public String getReason(){ return reason; }   
    public Contact[] getContacts(){ return contacts; }   
    public Location getLocation(){ return location; }   
    public Date getStartDate(){ return startDate; }   
    public Date getEndDate(){ return endDate; }   
       
    public void setLocation(Location location){ this.location = location; }   
       
    public String toString(){   
        return "Appointment:" + "\n    Reason: " + reason +   
    "\n    Location: " + location + "\n    Start: " +   
            startDate + "\n    End: " + endDate + "\n";   
    }   
}   
  
interface Location extends Serializable{   
    public String getLocation();   
    public void setLocation(String newLocation);   
}   
  
class ChangeLocationCommand implements UndoableCommand{   
    private Appointment appointment;   
    private Location oldLocation;   
    private Location newLocation;   
    private LocationEditor editor;   
       
    public Appointment getAppointment(){ return appointment; }   
       
    public void setAppointment(Appointment appointment){ this.appointment = appointment; }   
    public void setLocationEditor(LocationEditor locationEditor){ editor = locationEditor; }   
       
    public void execute(){   
        oldLocation = appointment.getLocation();   
        newLocation = editor.getNewLocation();   
        appointment.setLocation(newLocation);   
    }   
    public void undo(){   
        appointment.setLocation(oldLocation);   
    }   
    public void redo(){   
        appointment.setLocation(newLocation);   
    }   
}   
  
interface LocationEditor{   
    public Location getNewLocation();   
}   
  
class LocationImpl implements Location{   
    private String location;   
       
    public LocationImpl(){ }   
    public LocationImpl(String newLocation){   
        location = newLocation;   
    }   
       
    public String getLocation(){ return location; }   
       
    public void setLocation(String newLocation){ location = newLocation; }   
       
    public String toString(){ return location; }   
}   
  
interface UndoableCommand extends Command{   
    public void undo();   
    public void redo();   
}   
  
  
分享到:
评论

相关推荐

    Command设计模式搭建的框架小例子

    在Command模式中,主要涉及到以下几个角色: 1. 命令接口(Command):定义了命令的基本方法,通常是Execute,执行具体的业务逻辑。 2. 具体命令(Concrete Command):实现了命令接口,负责绑定接收者并定义执行的...

    Command模式(Java设计模式)

    Command模式是一种行为设计模式,它将请求封装为一个对象,从而使你可用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。在Java编程中,这种模式被广泛应用于实现命令行操作、GUI事件...

    设计模式之Command模式和代码实现

    在给定的例子中,通过引入Command模式,我们可以更容易地扩展遥控器的功能,增加新的电器或操作,而不会影响现有的代码结构。同时,这种模式还使得命令的发起者(遥控器)和命令的执行者(电器)之间的依赖关系变得...

    设计模式--命令模式java例子

    命令模式的核心是将请求者(Invoker)与执行者(Receiver)解耦,通过引入命令(Command)接口和具体命令(Concrete Command)类来实现。在该模式中,有四个主要角色: 1. **命令(Command)接口**:定义了一个接收...

    命令模式command pattern

    在这个例子中,命令模式使得我们可以很容易地添加新的命令,只需创建一个新的具体命令类并实现Command接口。同时,调用者(RemoteControl)和接收者(Light)之间完全解耦,增强了系统的扩展性和可维护性。 此外,...

    Command命令模式介绍.docx

    通过上述例子可以看出,Command命令模式能够有效地将请求发送方与接收方解耦。这种方式不仅使得代码更加清晰,也更容易扩展和维护。例如,如果需要添加一个新的命令,只需创建一个具体的命令类即可,无需修改原有的...

    C++设计模式代码资源23_Command_命令模式.zip

    2. **Concrete Command(具体命令)**:实现了Command接口,绑定一个接收者对象并存储与特定操作相关的任何信息。当调用`execute()`方法时,具体命令会调用接收者的相应操作。 3. **Invoker(调用者)**:负责调用...

    C++ Command模式

    Command模式是软件设计模式中的一种行为模式,它在23种经典设计模式中排名第十九,主要用来封装命令请求。这个模式的核心思想是将一个请求封装为一个对象,从而让我们可以使用不同的请求、队列或者日志请求,以及...

    设计模式之Command

    Command模式是一种行为设计模式,它将请求封装为一个对象,从而使你可用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。在Java编程中,这种模式常用于解耦调用者和接收者,使得系统...

    各个版本的 设计模式 带例子

    - **命令模式(Command)**:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志;以及支持可撤销的操作。 - **迭代器模式(Iterator)**:提供一种方法顺序访问一个...

    java 23种设计模式及具体例子

    * 命令模式(Command) * 备忘录模式(Memento) * 状态模式(State) * 访问者模式(Visitor) * 中介者模式(Mediator) * 解释器模式(Interpreter) 二、java 的 23 种设计模式 java 中的 23 种设计模式可以...

    Command(命令)模式[定义].pdf

    在给定的例子中,我们看到了Command模式的基本组成部分: 1. **Command接口/抽象类**:这是模式的核心,定义了所有命令必须实现的`execute()`方法。在例子中,`Command`类是一个抽象类,但通常可以是一个接口。这...

    Java 23种设计模式及例子

    18. **命令模式**(Command) - **描述**:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。 - **示例**:撤销操作功能。 19. **备忘录...

    Command命令模式介绍[参照].pdf

    通过Command模式,我们可以将请求封装为一个对象,使得请求者与执行者之间解耦,同时也方便了请求的记录、撤销/重做、事务处理等复杂操作。 Command模式的核心结构包括以下几个角色: 1. 命令接口(Command):...

    Head First 设计模式 (六) 命令模式(Command pattern) C++实现

    在这个例子中,`ConcreteCommand1`和`ConcreteCommand2`实现了`Command`接口,它们分别对应接收者`Receiver`的不同操作。`Invoker`作为调用者,可以设置不同类型的命令并调用`execute()`方法。 通过命令模式,我们...

    c#设计模式源码例子

    本压缩包文件“c#设计模式源码例子”提供了一组C#实现的设计模式示例,通过分析这些源码,我们可以深入理解并掌握各种设计模式的精髓。 首先,我们来看看几种主要的设计模式类别:创建型、结构型和行为型模式。 1....

    设计模式例子文档,简单易学

    这份名为"设计模式例子文档,简单易学"的资源,显然是为了帮助开发者更直观、更快速地理解和应用设计模式。设计模式并非具体的代码或库,而是一种通用的解决方案模板,可以在不同的软件开发过程中复用,以提高代码的...

    C#面向对象设计模式纵横谈(15):(行为型模式) Command 命令模式 (Level 300)

    在Command模式中,主要有四个角色: 1. **命令接口(Command)**:定义了一个执行操作的接口。每个命令都是实现了这个接口的具体类,规定了执行的操作。 2. **具体命令(Concrete Command)**:实现了Command接口,它...

    c++设计模式小例子

    2. **适配器模式(Adapter Mode)**:适配器模式允许不同接口的类之间进行通信。在`AdapterMode`文件中,你会学习如何将已有类的接口转换为客户期望的接口,使得两个不兼容的接口能够协同工作。 3. **中介者模式...

    设计模式-命令模式(C#)代码

    2. **具体命令(Concrete Command)类**:实现了命令接口,将一个接收者对象绑定到操作上。它通常包含一个对接收者的引用,并实现`Execute()`方法来调用接收者的相应操作。例如,假设我们有一个`Light`类作为接收者...

Global site tag (gtag.js) - Google Analytics