Java instantiation class and java instance

Source: Internet
Author: User

Java instantiation class and java instance

In Java, do you still set the new object unchanged?

When there are more projects, the amount of code writing will naturally increase, and the design pattern will gradually become apparent.

How can I make the written class instantiation action, high cohesion, low coupling, and a certain degree of scalability?

This article tries to start with several sections of fresh code to present different Java instantiation classes.

The following code is taken from the source code of com. google. zxing:

public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException {        Object writer;        switch(format.ordinal()) {        case 1:            writer = new AztecWriter();            break;        case 2:            writer = new CodaBarWriter();            break;        case 3:            writer = new Code39Writer();            break;        case 4:        case 10:        case 13:        case 14:        default:            throw new IllegalArgumentException("No encoder available for format " + format);        case 5:            writer = new Code128Writer();            break;        case 6:            writer = new DataMatrixWriter();            break;        case 7:            writer = new EAN8Writer();            break;        case 8:            writer = new EAN13Writer();            break;        case 9:            writer = new ITFWriter();            break;        case 11:            writer = new PDF417Writer();            break;        case 12:            writer = new QRCodeWriter();            break;        case 15:            writer = new UPCAWriter();            break;        case 16:            writer = new UPCEWriter();        }        return ((Writer)writer).encode(contents, format, width, height, hints);    }
  • The BarcodeFormat is as follows:
public enum BarcodeFormat {    AZTEC,    CODABAR,    CODE_39,    CODE_93,    CODE_128,    DATA_MATRIX,    EAN_8,    EAN_13,    ITF,    MAXICODE,    PDF_417,    QR_CODE,    RSS_14,    RSS_EXPANDED,    UPC_A,    UPC_E,    UPC_EAN_EXTENSION;    private BarcodeFormat() {    }}
  • The function provided by the source code is to output information through several different types of bar codes Wirter as a bit matrix and then output it to the image to form various types of bar codes that can be seen everywhere.
  • BitMatrix bitMatrix = new MultiFormatWriter().encode(_text, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints);MatrixToImageWriter.writeToFile(bitMatrix, qrcodeFormat, QrcodeFile);
  • The source code author used the New enum enumeration class introduced in JDK 1.5 and compiled the BarcodeFormat class, which defines the attributes of different types of bar codes.
  • Call MultiFormatWriter. encode () to instantiate a specific class based on the serial number of the input parameter BarcodeFormat. xx in the enumeration class.
  •        switch(format.ordinal()) {        case 1:            writer = new AztecWriter();            break;        case 2:            writer = new CodaBarWriter();            break;        case 3:            writer = new Code39Writer();            break;       ...............
  • These bar code Writer classes also implement two encode () Methods of the abstract interface Writer.
  • public interface Writer {    BitMatrix encode(String var1, BarcodeFormat var2, int var3, int var4) throws WriterException;    BitMatrix encode(String var1, BarcodeFormat var2, int var3, int var4, Map<EncodeHintType, ?> var5) throws WriterException;}
  • The specific bar code Wirter class adopts different logic based on different types of bar code rules.
  • Users do not need to pay too much attention to the internal implementation. They just need to generate a bar code that is suitable for entry. In the above example, the QR code is implemented.

Let's take a look at the method code of the classic MVC Framework Webwork dynamic instantiation class:

   private static Configuration getDefaultConfiguration () {            if (defaultImpl == null) {                defaultImpl = new DefaultConfiguration();                try {                    String className = getString("webwork.configuration");                    if (!className.equals(defaultImpl.getClass().getName())) {                        try {                            defaultImpl = (Configuration) ObjectFactory.getObjectFactory().buildBean(Thread.currentThread().getContextClassLoader().loadClass(className));                        } catch (Exception e) {                            LOG.error("Could not instantiate configuration", e);                        }                    }                    return defaultImpl;                } catch (IllegalArgumentException localIllegalArgumentException) {                }            }        }
  • The source code is taken from webwork-core. Many readers may not have heard about Webwork, but Struts should be like this. The core of Struts2 is rewritten from Webwork.
  • The functions provided by the above source code are to instantiate the configuration file read class defined by the user. This definition is in the configuration file.
  • The source code author uses Thread here. currentThread (). getContextClassLoader (). the class loader in the loadClass (className) thread dynamically instantiates the read class of the custom configuration file, which is the most efficient way.
  • Delegate chain of the Class Loader: SystemClassloader-> ExtensionClassloader-> BootstrapClassloader
  • The ClassLoader on the left of the delegate chain can naturally use the class loaded by the ClassLoader on the right. The class loading mechanism is to determine whether the class is loaded by itself, and the parent is not being asked.
  • These three class loaders correspond to the compiler to find the priority level and different paths of class files:
  • BootClassLoader is written in C ++. It loads classes from the % jre %/lib directory, or uses the-Xbootclasspath specified directory to load classes during runtime. Is the top priority for the compiler to find the class.
  • ExtClassLoader loads classes from the % jre %/lib/ext directory, or uses-Djava. ext. dirs to specify a directory for loading during runtime. Is the place where the compiler first looks for the class.
  • SystemClassloader is also the AppClassloader we often call. It corresponds to the current path, so it is also the place where the compiler finds the class by default.
  • In normal times, Class. forname () used in the project will start with BootstrapClassloader, which is the most resource-consuming.
  • The source code author uses the Thread class loader, corresponding to SystemClassloader, which is undoubtedly the most efficient.

The night is already deep. Do you feel a little bit after reading it.

If you do not like to abstract all things of time into the computer world, maybe the programmer is just a means of making a living, and you may not realize the beauty of code.

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.