Effective Java reading notes-Creating and destroying objects (i)

Source: Internet
Author: User
Tags protected constructor

Class typically provides a public constructor method that allows the client to obtain an instance of itself (a class). However, when creating an object, you should first consider using the static factory method instead of the constructor to return an instance. Using a static factory method instead of a public constructor has several advantages:

Static factory methods have (different) names

Constructor methods all have the same name, which is the name of the class. The method of distinguishing different constructors is determined by the signature of the observation method. The signature of a method includes the method name, the type of the method parameter, the number, and the order, and the return type of the method is not part of the method signature. It is not possible to distinguish different constructors by constructor method names, which can only be distinguished by the different parameters, in which case (in special cases, there may be parameters of the same type and number but different in order, at this time different constructor methods) often do not clearly distinguish between different constructor methods, not too intuitive to create a difficult to understand situation. Static factory methods can use different names, which are intuitive and easy to understand.

For example: the BigInteger (Int,int,random) constructor method may return a prime number, and you can use a static factory method to return an instance: Biginteger.probableprime, which is more straightforward.

The static factory method does not have to create a new object each time it is called

In many cases, each call to the factory method requires the same instance, so you can use a pre-built instance or cache the built-in instance for reuse. This saves space and time by not having to rebuild new instances every time. Like string, the basic type of wrapper class, biginteger,bigdecimal such immutable classes, once the instances of these classes are created, the instance will not change. This immutable class is appropriate for this situation.

A static factory method can return an object of any subtype of the original return type

When building an instance with a constructor method (using the new operator), only instances of the class itself can be returned. The use of static factory methods can return objects of sub-types, greatly increasing flexibility.

For example, the Java.util.EnumSet class introduced in Java 1.5 does not have a public constructor, only a static factory method. Enumset has two implementation classes, namely, Regalarenumset and Jumoboenumset. Two. Which implementation class is returned depends on the parameters of the static factory method, when the underlying enumeration type element is 64 or less using the Regalarenumset implementation, and the Jumoboenumset implementation is used when the value is greater than or equal to 65. Both implementations do not need to be public (common) classes, which hides the specific implementation. You can continue to increase or decrease the number of implementation classes, thus increasing flexibility, and class users no longer have to focus on implementation details.

In addition to the subclass above, there is a similar interface-oriented programming idea. The static factory method return type can be qualified as an interface, and a specific return object can be used as long as the interface is satisfied. Specifically, the return object can be required to meet List<t>, the actual return type can be arraylist<t>,linkedlist<t>, etc. to implement the type of the list interface. The user only needs to focus on the interface.

The class returned by the static factory method may not exist when writing a static factory method, which is the basis of the service provider framework (the services provider framework). JDBC is a service provider framework.

Static factory methods you can make your code more concise when you create an instance of a parameterized type (older version)

When you create an instance of a parameterized class (a generic Class), you must indicate the type in the case of a low version, even if the type parameter is obvious. For example:

Map<string,list<string>> m=new hashmap<string,list<string>> ();

In the case of static factory methods, the compiler can directly do type deduction, thereby eliminating the case of specifying type parameters. The static Factory method is:

public static <K,V> hashmap<k,v> newinstance () {return new hashmap<k,v> (); }

PS: In the higher version of Java in the direct call to the constructor is no longer necessary to specify the type parameters, here is just a reading notes!!! At the same time, the static factory method can be inferred in this case.

There are drawbacks to using the static factory method with respect to directly invoking the constructor method:

Disadvantage one: If the class does not contain a public or protected constructor, it cannot be inherited.

Disadvantage two: The static factory method is just a different static method, not a special mechanism. As a result, users can be confused, it may confuse the user, it is unclear how the class is instantiated. But there are several common specifications that can help users, and static factory methods have some idiomatic names, such as Valueof,of,getinstance,newinstance,gettype,newtype.

In summary, both the constructor and the static factory approach are beneficial.

Effective Java reading notes-Creating and destroying objects (i)

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.