Three brothers' factory method model (3)

Source: Internet
Author: User
3. Complete Solution

Sunny developers decided to use the factory method mode to design the logger. Its basic structure is shown in 3:

Figure 3 log recorder Structure

In Figure 3, the logger interface acts as an abstract product. Its sub-classes filelogger and databaselogger act as specific products, the loggerfactory interface acts as an abstract factory, and its sub-classes fileloggerfactory and databaseloggerfactory act as specific factories. The complete code is as follows:

// Logger interface: Abstract product interface logger {public void writelog ();} // Database Logger: specific product class databaselogger implements logger {public void writelog () {system. out. println ("database logging. ") ;}}// File logger: the specific product class filelogger implements logger {public void writelog () {system. Out. println (" file logging. ") ;}}// Logger factory interface: Abstract Factory interface loggerfactory {public logger createlogger () ;}// Database Logger factory class: the specific factory class databaseloggerfactory implements loggerfactory {public logger createlogger () {// connect to the database, the code is omitted // create the database logging object logger = new databaselogger (); // initialize the Database Logger with the Code omitted return logger; }}// file logger factory class: specific factory class fileloggerfactory implements loggerfactory {public logger createlogger () {// create a file logger object logger = new filelogger (); // create a file with the Code omitted return logger ;}}

Write the following client test code:

Class client {public static void main (string ARGs []) {loggerfactory factory; logger; factory = new fileloggerfactory (); // you can introduce a configuration file to implement logger = factory. createlogger (); logger. writelog ();}}

Compile and run the program. The output result is as follows:

File logging.

 

4. Reflection and configuration file

To make the system more flexible and scalable, sunny developers decided to refactor the logger client code, this allows you to change or add a new logging method without modifying any client code.

In the client code, the new keyword is no longer used to create factory objects. Instead, the class names of specific factory classes are stored in configuration files (such as XML files, get the class name string by reading the configuration file, and then use the Java reflection mechanism to generate an object based on the class name string. Two technologies are required throughout the implementation process: Java reflection mechanism and configuration file reading. The configuration file of the software system is usually an XML file. We can use dom (Document Object Model), SAX (Simple API for XML), Stax (streaming API for XML) and other technologies to process XML files. For details about Dom, sax, Stax, and other technologies, you can refer to other relevant materials and will not extend them here.

Extension

For more information about Java and XML, read "Java XML programming guide" by Tom Myers and Alexander nakhimovsky or visit "Java XML technology topics" in developer works in China ", reference link:

Http://www.ibm.com/developerworks/cn/xml/theme/x-java.html

Java reflection (Java reflection)It refers to a mechanism for obtaining information about classes with known names or existing objects when the program is running, including methods, attributes, and parent classes of classes, it also includes instance creation and instance type determination. The most frequently used class in reflection is class. the instance of the class represents the classes and interfaces in the running Java application, and its forname (string classname) the method can return the class object associated with the class or interface with the given string name, and then create a new instance of the class represented by this object through the newinstance () method of the Class Object, that is, the instance of the class is obtained through a class name string. To create a String object, the Code is as follows:

// Generate an Instance Object using the class name and return Class C = Class. forname ("string"); object OBJ = C. newinstance (); Return OBJ;

In addition, the JDK also provides the java. Lang. Reflect package, which encapsulates other reflection-related classes. Only the simple reflection code above is used here and will not be extended here.

Sunny Developers created the configuration file config. XML in the following XML format to store the factory class name of a specific logger:

<!— config.xml --><?xml version="1.0"?><config><className>FileLoggerFactory</className></config>

To read the configuration file and generate an object through the class name string reflection stored in it, sunny developers developed a tool class named xmlutil. The detailed code is as follows:

// Tool class xmlutil. javaimport javax. XML. parsers. *; import Org. w3C. dom. *; import Org. XML. sax. saxexception; import Java. io. *; public class xmlutil {// This method is used to extract a specific class name from the xml configuration file and return an instance object public static object getbean () {try {// create the DOM Document Object documentbuilderfactory dfactory = documentbuilderfactory. newinstance (); documentbuilder builder = dfactory. newdocumentbuilder (); document DOC; Doc = builder. parse (new file ("config. XML "); // get the text node containing the class name nodelist NL = Doc. getelementsbytagname ("classname"); node classnode = NL. item (0 ). getfirstchild (); string cname = classnode. getnodevalue (); // generate an Instance Object using the class name and return Class C = Class. forname (cname); object OBJ = C. newinstance (); Return OBJ;} catch (exception e) {e. printstacktrace (); return NULL ;}}}

With the xmlutil class, you can modify the client code of the logger without directly using the new keyword to create a specific factory class, instead, the class names of specific factory classes are stored in XML files, and objects are instantiated using the static factory method getbean () of the xmlutil class. The code is modified as follows:

Class client {public static void main (string ARGs []) {loggerfactory factory; logger; factory = (loggerfactory) xmlutil. getbean (); // The return type of getbean () is object, which requires forced type conversion logger = factory. createlogger (); logger. writelog ();}}

After the xmlutil class and xml configuration file are introduced, to add a new logging method, you only need to perform the following steps:

(1) The new logger must inherit the abstract logger;

(2) Add a new logger factory, inherit the abstract loggerfactory of the logger factory, implement the factory method createlogger (), and set the initialization parameters and environment variables, returns the specific logger object;

(3) modify the configuration file config. XML to replace the class name string of the newly added factory class of the logger with the original factory class name string;

(4) Compile the new log recorder class and the factory class of the specific logger. Run the client test class to use the new log recording method. The original class library code does not need to be modified, it fully complies with the "open and closed principles ".

The above reconstruction can make the system more flexible. Because many design modes focus on the scalability and flexibility of the system, they define the abstraction layer and declare business methods in the abstraction layer, put the implementation of business methods in the Implementation Layer.

Thoughts

Some people say: the reflection mechanism can be used in client code to generate product objects and abstract types can be used to define product objects. This also ensures the flexibility and scalability of the system, to add a new product category, you do not need to modify the source code. You only need to use it as a subclass of the abstract product category and then modify the configuration file. You do not need to abstract factory classes and specific factory classes.

Think about the feasibility of this approach? If feasible, is there a problem with this approach? Why?

【Author】 Liu WeiHttp://blog.csdn.net/lovelion]

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.