On the optimization of Factory mode (Factory pattern) and Java reflection mechanism

Source: Internet
Author: User

<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); >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,</span>

The advantage is that it will make the user more user-friendly, without concern for the specific creation logic

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


From the UML diagram above, we have set up a shape interface and implemented three subclasses, and we passed the shapefactory to return different subclass instances through the Factorypatterndemo to test. The logic is simple and no longer detailed.

public class Shapefactory {
	
   //Getshape method Gets the object of the shape type 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 above surface shapefactory implementation, we think that if we add a subclass implementation, then shapefactory must modify the source code, and recompile, this is not the result we want. If you can not change the content of the shapefactory, but will be called to write the subclass in the configuration file, so that Shapefactory received from the configuration file needs to return the subclass name, return the corresponding subclass instance. Here, you may sound familiar, this is not very similar to the dependency injection in spring, can think of here that you are very powerful. Yes, this requires a Java reflection mechanism (the internal principle of spring dependency injection is dependent on the Java Reflection mechanism), and the Java.lang.Class class shines.

For the Java.lang.Class class, we can use the Class.forName method with the class's detailed name (including the package name) to get a class of this category, then you can through the class class to carry out a series of operations, Instantiate a class object of this class newinstance () (invoke constructor instantiation without parameters), view his constructor constructor, method methods, member Variable field, Execute method (You may need a class in Java.lang.reflect).

Back above, how do we optimize the factory model above, the idea is to first put the name of the subclass to be called in the configuration file (the benefit is to change the call does not need to change the other code), and then in the factory to parse the class with class, and the instantiation of the return. Finally in the demo in the call. 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 block
			e.printstacktrace ();
			System.out.println ("Not getting the class properly");
		}
		try {
			targetshape= (Shape) oneclass.newinstance ();
		} catch (Exception e) {
			//TODO auto-generated catch Block
			e.printstacktrace ();
			SYSTEM.OUT.PRINTLN ("Cannot create an instance 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 about simple Factory mode applications.
Understanding this, it is not difficult to understand spring's IOC technology, spring's configuration file replaced with XML files, and the design is more complex, calling the program into the so-called spring container, of course, this is the cornerstone of spring design, the superstructure is still very complex.

Related Article

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.