Design pattern of the actual application of the four: simple factory model

Source: Internet
Author: User
Tags java web
definition of simple factory pattern
The simple factory pattern is a very basic design pattern. Java.text.DateFormat in the Java API the getdateinstance that obtains a specific subclass instantiation is the application of a simple factory; SAX1 in the library. Javax.xml.parsers.DocumentBuilderFactory and Javax.xml.parsers.SAXParserFactory are also examples of simple factory applications, newinstance Is their own simple factory approach; the org.xml.sax.helpers.XMLReaderFactory in the SAX2 library creates a XMLReader instance of the product class Createxmlreader is also the specific factory method of the simple factory pattern; Apache The workbookfactory in the POI Library is a very standard simple factory model that can be used as an example of our study of simple factory models.
Simple factory model, also known as static Factory method mode. Gof is not included in the list of 23 design Patterns in design mode: The foundation of reusable object-oriented software. In many literatures, it is only a special form of the factory method pattern, so it belongs to the creation pattern as the factory method pattern. Freelance Tom McFarlin The simple factory pattern on Tutsplus to define: "The simplicity Factory patterns returns a specific set of data or a specific CL Ass based on its input. "The simple factory decides to return a specific set of data or an instance of a particular class based on the parameters passed in. "The simple factory pattern is defined in the CSCI 3132 course:" Pull the code that builds the instances out and put it into a separate class. "The translation is:" Migrate the code that is responsible for creating the object into a separate class. Dr Shanhong's definition of a simple factory pattern in Java and schema is as follows: "A simple factory pattern is a factory class that determines which instances of the product class are created based on incoming parameters." "
The author prefers to CSCI 3132 's definition of a simple factory.
why simple Factory mode.
Simple factories help our code to be abstracted, making our projects easy to maintain, easy to read, and keeping our code neat. This may cause our project to introduce more files, but each file will have fewer code.
This means that each file is more clearly used, not only for ourselves, but also for future developers.
the use of simple Factory mode
Multiple clients require an object of the same type. Maintains the consistency of object initialization. system error Information Report requirements
Each system requires a way to report an error message. Java Web applications that are small white programmers are no exception: After the project deployment, small white can not use breakpoints in the way to their own system for error tracking, the system needs a kind of error reporting mechanism to allow themselves to the health of the system to have a good idea; In addition, the actual pressure of the system's concurrent volume, the implementation of important interface time, The data that is not accurately known during the coding period is also of concern to little white students. Little white students have designed a system error information reporting mechanism.
Little white classmate Design tracking interface trace source code is as follows:
Public interface Trace {
      //turn in and off debugging public
      void Setdebug (Boolean debug);
      Write out a debug message public
      void Debug (String message);
      Write out a error message public
      void error (String message);

Xiao Bai wrote two Trace implementations according to his needs. One is filetrace, which writes trace information to a file:
public class Filetrace implements Trace {
          
      private java.io.PrintWriter pw;
      Private Boolean debug;
      Public Filetrace () throws Java.io.IOException {
            //a real filetrace would need to obtain the filename somewhere
            // For the example I ' ll hardcode it
            pw = new Java.io.PrintWriter (New Java.io.FileWriter ("C:\trace.log"));
      Public
      void Setdebug (Boolean debug) {
            this.debug = Debug;
      }
      public void Debug (String message) {
            if (debug) {  //Only print if Debug is True
                  pw.println ("Debug:" + message);
                  Pw.flush ();
            }
      public void error (String message) {
            //always print out errors
            pw.println (' ERROR: ' + message);
            Pw.flush ();
      }

The other is systemtrace, which writes trace information to the command line:
public class Systemtrace implements Trace {
      private boolean debug;
      public void Setdebug (Boolean debug) {
            this.debug = Debug;
      }
      public void Debug (String message) {
            if (debug) {  //Only print if Debug is True
                  System.out.println ("Debug: "+ message);
            }
      }
      public void error (String message) {
            //always print out errors
            System.out.println (' ERROR: ' + message); 
  
   }
}
  

In the code that needs to be tracked, the code for small white uses trace is as follows:
... some code ...
Trace log = new Systemtrace ();
... code ...
Log.debug ("Entering Loog");
... etc...

Analysis of the system error information report
Now if little white wants to implement the trace in the application, you must modify each class that instantiates trace. This workload depends on the number of classes that use Trace, and if the system is slightly larger, it will be a lot of effort. This brings a lot of inconvenience to the subsequent system maintenance. In addition, some classes use the Systemtrace, some use the filetrace, the system Trace use confusion, inconsistent.
We introduced a simple factory model to help Xiao Bai optimize the system error information reporting mechanism. The advantages of using a simple factory here are:
A simple factory provides an elegant way to abstract your code, dramatically reducing the visual clutter of your code. A simple factory allows you to introduce more professional, focused classes that specialize in a single purpose. Simple factories enhance the maintainability of the code because the instantiation of various implementation classes is concentrated in a single place.
"System Error Information Report" Class design


system error Information report sequence diagram


"System error Information Report" Source code implementation
Simple factory Tracefactory class source code is as follows:
public class Tracefactory {public
      static Trace Gettrace () {
            try {return
                  new Filetrace ();
            } catch (java. Io. IOException ex) {
                  Trace t = new Systemtrace ();
                  T.error ("Could not instantiate Filetrace:" + ex.getmessage ());
                  return t;}}}

Client Invocation Example:
... some code ...
Trace log = new Tracefactory.gettrace ();
... code ...
Log.debug ("Entering Loog");
... etc...

As you can see, a simple factory is useful when you are not sure which Trace implementation is instantiated specifically. You just throw the details to the simple factory.
In the above example, the system does not know whether to create a filetrace or a systemtrace instance. Your object simply needs to easily use the Trace object from the factory, which is the specific implementation of this object. How to instantiate. These details will be given to a simple factory to complete.

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.