The plant pattern (Factory pattern) and the Java Reflection Mechanism optimization thinking

Source: Internet
Author: User

Gof's factory model is the most basic type of creation design pattern, which is suitable for creating different implementation subclasses of the same interface.

The advantage is that it will make the user more user-friendly and not be concerned with the specific creation logic

The disadvantage is that each additional subclass of an interface must modify the relevant logic of the engineering class (we will use the Java reflection mechanism to optimize it later)

As seen from the UML diagram above, we have set up a shape interface and implemented three subclasses, and we have passed shapefactory to return different subclass instances according to different names, and test through Factorypatterndemo. Logic is simple, no longer detailed.

public class Shapefactory {   //Use the Getshape method to get the shape type Object public shape   getshape (String shapetype) {      if ( ShapeType = = null) {         return null;      }      if (Shapetype.equalsignorecase ("CIRCLE")) {         return new CIRCLE ();      } else if (Shapetype.equalsignorecase (" RECTANGLE ")) {         return new RECTANGLE ();      } else if (Shapetype.equalsignorecase (" SQUARE ")) {         return new Square ();      }      return null;}   }

Based on the implementation of the above-mentioned shapefactory, we think that if we add a sub-class implementation, then Shapefactory must make corresponding changes to the source code, and re-compile, this is not the result we want. If you can not change the content of the shapefactory, but will need to call the subclass write in the configuration file how good, so that shapefactory from the configuration file to receive the subclass name that needs to be returned, return the corresponding subclass instance. Speaking of which, everyone may be familiar with the spring of dependency injection is not very similar to, can think of this shows you are very good. Yes, this requires a Java reflection mechanism (the inner principle of spring dependency injection is dependent on the reflection mechanism of Java), and the Java.lang.Class class shines.

For the Java.lang.Class class, we can use the Class.forName method to get a class with the class name (including the package name), after which we can do a series of operations with this class. Instantiate a class object of this class newinstance () (invoke constructor instantiation without parameters), view his constructor method constructor, method, member Variable field, Execute method (the class in Java.lang.reflect may be required).

Back up, how do we optimize the factory pattern above, the idea is to first put the name of the subclass to be called into the configuration file (the advantage is that when changing the call does not need to change the other code), and then in the factory with class to parse the class, and instantiate the return. Finally, the call is made in the demo. The idea is simple.

The properties file is as follows:

Shape.classname=factorypattern.rectangle

The factory code is as follows

public class Shapefactory {public Shape getshape (String shapeclassname) {shape targetshape=null; Class oneclass=null;try {oneclass=class.forname (shapeclassname);} catch (ClassNotFoundException e) {//TODO Auto-generated catch Blocke.printstacktrace (); SYSTEM.OUT.PRINTLN ("Cannot get the class correctly");} try {targetshape= (Shape) oneclass.newinstance ()} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); System.out.println ("instance not created correctly");} return targetshape;}

Call:

public static void Main (string[] args) {String targetclassname=classnameconfig.getproperty ("Shape.classname"); System.out.println ("Targetclassname:" +targetclassname); Shapefactory shapefactory=new shapefactory (); Shape Targetshape=shapefactory.getshape (targetclassname); Targetshape.draw ();}

This way, when you modify the calling subclass, you only need to modify the configuration file. Of course, there's no need to be so cumbersome for simple Factory mode applications.
Understanding this, it is not difficult to understand spring's IOC technology, Spring's configuration file for the XML file, and the design is more complex, the calling program into the so-called Spring container, of course, this is only the cornerstone of spring design, the superstructure is still very complex.

The plant pattern (Factory pattern) and the Java Reflection Mechanism optimization thinking

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.