Request sender and receiver decoupling--command mode (v)

Source: Internet
Author: User
6 Request Log

The request log saves the requested history and is typically stored permanently in the computer in the form of a log file . Many systems provide log files, such as Windows log files, Oracle log files, and so on, and log files can record user actions on the system, such as changes to the data. Request log files can achieve many functions, commonly used as follows:

(1) "The days of accidents", once the system failure, log files can provide a recovery mechanism for the system, in the request log file can record the user to the system every step of operation, so that the system can be successfully restored to a particular state;

(2) The request log can also be used to implement batch processing, in which a sequence of command objects, such as a command queue, can be stored in a request log file;

(3) All command objects in the command queue can be stored in a log file. Each command is executed to remove a corresponding command object from the log file to prevent the loss of requests due to power outages or system restarts, and to avoid the recurrence of certain commands when all requests are resend. Just read the request log file, and then continue to execute the remaining commands in the file.

When implementing the request log, we can serialize the command object to the log file , at which point the command class must implement the Java.io.Serializable interface. Here we use a simple example to illustrate the purpose of the log file and how to implement the request log:

The Sunny software company has developed a Web site profile management tool that allows you to add a deletion to a Web site configuration file through a visual interface, which is designed using command mode, as shown in Figure 6:

Figure 6 Web Site configuration file Management tool structure chart

Now sunny software company developers want to log the action requests for the configuration file in the journal file, and if the site is redeployed, you can modify the configuration file by simply executing the command object saved in the log file.

The complete code for this example looks like this:[Java] View plain copy import java.io.*;   import java.util.*;     //abstract command class, Because the command object needs to be written to the file, it implements the serializable interface    abstract class command implements  serializable {       protected string name; //command name         protected string args; //command Parameters         protected configoperator configoperator; //maintain references to recipient objects                public command (string name)  {            this.name = name;       }              public string getname ()  {            return this.name;        }              public void setname (String name)  {            this.name = name;        }              public void  Setconfigoperator (configoperator configoperator)  {            this.configOperator = configOperator;       }              //declares two abstract execution methods execute ()         public abstract void execute (String args);        Public abstract void execute ();  }     //Add command class: Specific commands    class insertcommand extends command {       public  InsertCommand (StriNg name)  {           super (name);        }              public void  execute (String args)  {           this.args  = args;           configoperator.insert (args);        }               Public void execute ()  {            Configoperator.insert (This.args);       }  }     // Modify command class: Specific command    class modifycommand extends command {        public modifycommand (string name)  {            super (name);       }               Public void execute (String args)  {            this.args = args;            Configoperator.modify (args);       }               public void execute ()  {            configoperator.modify (This.args);       }  }      //omitted Delete command class deletecommand     //Profile Action class: request recipient. Because the object of the Configoperator class is a member object of the command, it will also be written to the file with the command object, so configoperator also needs to implement the Serializable interface    class  ConfigOperator implements Serializable {       public  Void insert (String args)  {           system.out.println ("Add new node:"  + args);       }              public  Void modify (String args)  {            SYSTEM.OUT.PRINTLN ("Modify node:"  + args);       }               public void delete (String args)  {    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Delete node:"  + args);        }  }     //Profile Settings window class: Request Sender    class  configsettingwindow {       //defines a collection to store the command object for each operation         private ArrayList<Command> commands = new ArrayList<Command> ( );   &NBSP;&NBsp;  private command command;           // Inject specific command objects        public void setcommand (Command command)  {            this.command = command;       }              //Execute configuration file Modification command, Add command objects to the command set at the same time        public void call (String args)  {            command.execute (args);            commands.add (command);       }               //Record request log, generate log file, write command collection to log file         public void save ()  {            Fileutil.writecommands (commands);       }               //extracts the command collection from the log file and loops through the Execute () method of each Command object to implement the configuration file reset        public void  recover ()  {           ArrayList list;            list = fileutil.readcommands ();                       for  (object obj : list)  {                 (Command) obj. Execute ();                   }  }     //Tools class: File Operation class    class  fileutil {       //writes a collection of commands to the log file        public  stAtic void writecommands (arraylist commands)  {            try {                fileoutputstream file = new fileoutputstream ("Config.log");                //create an object output stream to write an object to a file                 ObjectOutputStream objout = new  ObjectOutputStream (New bufferedoutputstream (file));                //writes an object to a file                 objout.writeobject (commands);                objout.close ();                } &nBsp         catch (exception e)  {                    system.out.println ("command save failed.) ");                      e.printstacktrace ();                }       }               //extract command set from log file        public static ArrayList  Readcommands ()  {           try {                fileinputstream file = new  fileinputstream ("Config.log");                //create an object input stream withTo read objects from files                objectinputstream  objin = new objectinputstream (New bufferedinputstream (file));                                //the objects in the file and converts them to ArrayList types                 ArrayList commands =  (ArrayList) objin.readobject ();                objin.close ();               return commands;               }            catch (exception e)  {              &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("command read failed.) ");                    e.printstacktrace ();                    return null;                    }               }  }  

Write the following client test code:[Java] View Plain Copy class client {       public static void  Main (string args[])  {           configsettingwindow  csw = new configsettingwindow ();  //definition request Sender             command command; //define Command Objects             configoperator co = new configoperator ();  //definition request recipient                        //Four changes to configuration files            command = new insertcommand ("add");            command.setconfigoperator (CO);            csw.setcommand (command);           &Nbsp;csw.call ("Home");                       command = new insertcommand ("add");            command.setconfigoperator (CO);            csw.setcommand (command);           csw.call ("Port number");                       command = new modifycommand ("Modified");            command.setconfigoperator (CO);            Csw.setcommand (command);           csw.call ("Home page");                        command = new modifycommand ("Modified");            Command.setconfigoperator (CO);           csw.setcommand ( command);                    csw.call ("port number");                       system.out.println ("----------------------------");           system.out.println ("Save Configuration");            csw.save ();                           system.out.println ("------------ ----------------");            system.out.println (" Restore Configuration " );   &NBSP;&NBSP;&NBSP;&NBsp;    system.out.println ("----------------------------");             csw.recover ();         }   }  

Compile and run the program, and the output is as follows:

Add new node: Home

Add new node: port number

Modify Node: Home

Modify Node: port number

----------------------------

Save Configuration

----------------------------

Restore Configuration

----------------------------

Add new node: Home

Add new node: Port number

Modify node: Home

Modify Node: port number

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.