Application of reflection in factory Mode

Source: Internet
Author: User
Document directory
  • 2.1 use the reflection mechanism to input a specific "package. Class Name" on the client to dynamically create an instance
  • Fruit. Java
  • Apple. Java
  • Orange. Java
  • Factory. Java
  • Facotrydemo1.java
  • 2.2 dynamically create an instance with the configuration file
1. Preface

I have previously written a simple factory method for design patterns. In this article,"7. configurable simple factory instances", The client does not pass in the parameter, because the configuration file to be read has been defined in the factory. However, the disadvantage is that the flexibility is not enough. You must specify the items in the configuration file to be read. For example, the preceding definition defines that the items in the configuration file must be read.Implclass = edu. SJTU. erplab. yanmo. simplefactory. impl2This entry is assumed to have multiple entries in the configuration file. We want to pass in a simple parameter through the client.ImplclassThe instance cannot be dynamically called.

2. The text 2.1 uses the reflection mechanism to input a specific "package. Class Name" on the client to dynamically create an instance.

First define a fruit interface fruit, which contains an eat Method

Fruit. javaview code

package edu.sjtu.erplab.reflect;public interface Fruit {    public void eat();}

Then define two types of fruit apple and orange to inherit the fruit interface.

Apple. javaview code

Package edu. SJTU. erplab. Reflect; public class Apple implements fruit {@ override public void eat () {system. Out. println ("eat apple ");}}
Orange. javaview code

Package edu. SJTU. erplab. Reflect; public class orange implements fruit {@ override public void eat () {system. Out. println ("eat orange ");}}
Factory. javaview code

package edu.sjtu.erplab.reflect;public class Factory {    public static Fruit getInstance(String className)    {        Fruit fruit=null;        try {            fruit=(Fruit)Class.forName(className).newInstance();        } catch (Exception e) {            e.printStackTrace();        }         return fruit;    }}

Finally, the client dynamically creates a fruit instance by passing in a specific class name.

Facotrydemo1.java view code

Package Edu. SJTU. erplab. reflect; public class facotrydemo1 {public static void main (string [] ARGs) {// pass in the complete package through the interface instance of the factory class. class Name. Fruit F = NULL; F = factory. getinstance ("edu. SJTU. erplab. reflect. apple "); F. eat (); F = factory. getinstance ("edu. SJTU. erplab. reflect. orange "); F. eat ();}}

The first input is Apple's class name, and the second input is orange's thunder. Therefore, the result of running the Eat method twice is

Eat apple
Eat oranges

2.2 dynamically create an instance with the configuration file

Although the above operation code can obtain the interface instance through reflection, the complete package needs to be imported during the operation. class Name, and the user cannot know how many sub-classes an interface can use. Therefore, you can configure the required sub-class information in the form of an attribute file.

CreateFruit. PropertiesFile, the file content is:

apple=edu.sjtu.erplab.reflect.Appleorange=edu.sjtu.erplab.reflect.Orange

The complete package. Class Name is represented by a simple apple and orange in the property file, so that you can directly use the property name in use, without a long stringPackage. Class Name.

To use an attribute file, we need to create an attribute operation class. The specific implementation is as follows:

View code

Package Edu. SJTU. erplab. reflect; import Java. io. ioexception; import Java. io. inputstream; import Java. util. properties; public class init {public static properties getpro () {properties pro = new properties (); inputstream in = NULL; try {In = init. class. getresourceasstream ("fruit. properties "); // obtain resources under the package where this class is located. Pro. load (in);} catch (ioexception e) {// todo auto-generated Catch Block E. printstacktrace ();} finally {try {In. close ();} catch (ioexception e) {e. printstacktrace () ;}} return pro ;}}

This class is used to read the configuration file under the package where the class is located.Fruit. PropertiesAnd return the content in the specific configuration file.

Then, on the client, we only need to obtain the configuration file through the configuration file operation class and input the attribute name. The code example is as follows:

View code

Package Edu. SJTU. erplab. reflect; import Java. util. properties; public class factorydemo2 {public static void main (string ARGs []) {properties pro = init. getpro (); fruit F = NULL; // use reflection to create an object instance F = factory. getinstance (Pro. getproperty ("apple"); F. eat (); F = factory. getinstance (Pro. getproperty ("orange"); F. eat ();}}

We can see that here we only need to input pro to the factory method. getproperty ("apple"), and pro. getproperty ("apple") indicates that the key in the configuration file is the value corresponding to Apple, that is

Edu. SJTU. erplab. Reflect. Apple. Here, customers only need to know about Apple, instead of edu. SJTU. erplab. Reflect. Apple, which implements a good encapsulation.

 

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.