It takes only five minutes to finish reading objective Java and objective tivejava.

Source: Internet
Author: User

It takes only five minutes to finish reading objective Java and objective tivejava.

Valid Java

 

Create and destroy objects-consider replacing constructors with static factory methods

The constructor is the most basic and common method for creating an object instance. When using a class, most developers must first consider how to construct and initialize an object example, the constructor takes into account the constructor first. Therefore, when reading the documents in javadoc, the first concern is the constructor. Therefore, for classes, we usually provide a public (public) constructor to obtain instance objects of a class. Of course, in addition to this method, we can also provide a public static factory method for the class to return a class instance. For example:

public static Boolean valueOf(boolean b) {    return b ? Boolean.TRUE : Boolean.FALSE; }

In this example, the basic boolean Type value is converted into a reference of a Boolean object. (Note that the static factory method here is different from the factory method mode mentioned in the design mode.) in the first article of objective Java, let's take a look at the advantages of the static factory method over the constructor:1. The static factory method can have different names, and the code is clearer and easier to read.In the Framework Design, empty objects are usually considered for some tool classes to identify whether the object has been initialized. The constructors have the same names. A class can have only one constructor with the specified signature. When a class needs to provide multiple constructors, it is usually differentiated by the order of different parameter types, but its function names are still the same and cannot provide a high degree of discrimination. When a class requires multiple constructors with the same signature, consider replacing the constructor with a static factory method and carefully selecting names to highlight the differences between them. In this way, the static factory method has a name. by assigning a meaningful name, programmers who use this method can clearly understand the meaning of this method. (The method signature is composed of its name and the return type of all parameters, excluding its return type)2. Static factory methods do not have to create a new object each time they are called.For example, you can limit the number of objects created in the static factory method. When the number of objects exceeds the specified number, the objects in the cache are returned. Scenario: a new object is created every time the constructor is called. Obviously, Singleton also provides a static factory method to obtain instances. In addition, you can use = to replace the equals () method to improve the performance.3. The static factory method can return any child type objects of the original return type.Scenario: the constructor can only return instances of the current class, but cannot return instances of the subclass. This advantage is indeed very useful and can make full use of polymorphism to make the code more scalable. The factory method in the design mode is also reflected. You can return different subclass instances whose Types are Types based on the input parameter type.

public Types getType(String type) {...}

In this way, we have more flexibility when selecting the class of the returned object. This flexibility Application means that the API can return the object without changing the class of the object to public. Hiding the implementation class in this way will make the API concise. This technology is suitable for interface-based frameworks ). This interface-oriented programming also improves Software maintainability and performance.4. The static factory method simplifies the code when creating parameterized instances.Scenario: Java generic classes still need to write two type parameters during instantiation, which is very lengthy. The static factory method can help you improve this situation: for example, the following static factory method is provided in the HashMap class:

public static <k, v=""> HashMap<k, v=""> newInstance(){   return new HashMap<k, v="">();  }

So, the call should be like this:

HashMap<stirng, list<string="">> m = HashMap.newInstance();

This is usually required when a parameterized constructor is called.

HashMap<string, list<string="">> m = new HashMap<string, list<string="">>(); 

It is also worth mentioning that the class of the object returned by the static factory method does not exist when writing a class containing the static factory method. This flexible static factory method forms the foundation of the Service Provider Framework, such as JDBC APIs. The so-called service provider framework refers to a system in which multiple service providers implement the same service) to provide multiple implementations of such services for the client and decouple these implementations. The Service provider framework has three main components: 1. Service interface, which is implemented by the provider. 2. Provider Registration API (Provider Registration API), which is used by the system to register the implementation and allow the client to access them. 3. Service Access API, which is used by the client to obtain the Service instance. There is also the fourth available Interface, the Service Provider Interface, which is responsible for creating its Service implementation instance. If there is no service provider interface, the implementation registers according to the class name and instantiates it through reflection. For JDBC, Connection is its service interface, DriverManager. registerDriver is its provider registration API, DriverManager. getConnection is the service access API, and Driver is the service provider interface.

For example, two static factory methods (empty and preallocate) are provided to create an empty object and a String object with the specified allocation space. From the usage perspective, these static methods provide users with the ease to determine their functions and application scenarios, you do not need to search for each constructor and Its Parameter List in a group of overloaded constructor to find the constructor suitable for the current scenario.

In terms of efficiency, because a unique static null object is provided, the prefabricated static Null Object (emptyString) is directly used to determine whether the object instance is empty (isEmpty) the address of is compared with the current object. If it is the same address, you can confirm that the current instance is a null object. For the preallocate function, as the name suggests, this function pre-allocates a specified size of memory space. When this String instance is used later, you do not have to worry about frequent operations such as realloc (re-allocating memory) due to the assignment or appending of too many characters. 2. You do not have to create a new object each time you call them. Based on the code example above, because all empty objects share the same static empty object, this also saves more memory overhead. If it is an empty object constructed in strEmpty2 mode, when performing comparisons and other operations, more efficiency overhead will be incurred. In fact, Java uses the constant resource pool in the implementation of String objects based on the same optimization strategy. This advantage also applies to the single-instance mode. 3. Any child types of the original return type can be returned. In the collection interface of Java Collections Framework, a large number of static methods are provided to return the implementation types of the collection interface type, such as Collections. subList () and Collections. unmodifiableList. The returned interface is clear, but the user of the function does not need to know the specific implementation class. This not only greatly reduces the number of export classes, but also in the future, if we find that the implementation efficiency of a subclass is low or find a better data structure and algorithm to replace the current implementation subclass, the user of the Set interface will not have any impact. In this example, this book mentions that EnumSet returns an object instance through the static factory method without providing any constructor. In this case, it implements an optimization when returning classes, that is, if the number of enumerations is less than 64, the factory method returns a RegularEnumSet, which internally uses long (64bits in Java) to indicate different enumerated values. If the number of enumerations is greater than 64, the long array is used as the underlying support. However, the optimization of these internal implementation classes is transparent to users. 4. When creating parameterized instances, they make the code more concise. Map <String, String> m = new HashMap <String, String> (); Because Java cannot deduct the type in calling the constructor, therefore, the parameter type of the constructor cannot be used to instantiate the instantiated object of a specified type parameter. However, the static factory method can take advantage of the parameter type deduction to avoid the troubles caused by the repeated rewriting of the type parameter in one declaration. See the following 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.