Just five minutes to finish reading effective Java

Source: Internet
Author: User

Effective Java

Creating and destroying objects---consider replacing constructors with static factory methods

constructors are the most basic and most common way to create an object instance, most developers use a class, the first thing to consider is how to construct and initialize an object example, and the way to construct the first consideration is to do through the constructor function, So the first thing to focus on when looking at a document in Javadoc is the constructor. So, for a class, we typically provide a public constructor to get an instance object of a class. Of course, in addition to this approach, we can also do this by giving the Class A static factory method of public (static factory methods) to return an instance of a class. such as:

 Public Static Boolean ValueOf (boolean  b) {    return b?  Boolean.TRUE:Boolean.FALSE; }

) So, in the first chapter of effective Java, Let's see how the Static factory approach benefits from the constructor: 1. Static factory methods can have different names, the code is clearer and easier to read. in a framework design, an empty object is typically considered for some tool classes to tell if the object has been initialized. constructors are named consistently, and a class can have only one constructor that specifies a signature. When a class needs to provide more than one constructor, it is usually differentiated by the order of the different formal parameter types, but its function names are the same and cannot provide a high degree of sensitivity. Then, when a class requires more than one constructor with the same signature, consider replacing the constructor with a static factory method, and carefully select the name to highlight the difference between them. This static factory method has a name, and by giving it a meaningful name, programmers using the method can clearly understand the meaning of the method. (a method's signature (signature) consists of its name and the return type of all parameters, not 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, and return the objects in the cache when the specified number is exceeded. Scene: A new object is created each time the constructor is called. Obviously, we know that Singleton actually provides a static factory method to get the instance. In addition, you can use = = instead of the Equals () method to achieve improved performance. 3. The static factory method can return an object of any subtype of the original return type. Scenario: The constructor can only return an instance of the current class and cannot return an instance of the subclass. This advantage is really useful to take advantage of polymorphism and make the code more extensible. The factory method in design mode also manifests itself, and can return different subclass instances of type types according to the entry type.

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

This gives us more flexibility in choosing which class to return the object to, and the application of this flexibility is that the API can return the object without making the object's class public. Hiding the implementation class in this way makes the API concise. This technique is suitable for interface-based frameworks (interface-based framework). This interface-oriented programming also improves the maintainability and performance of the software. 4. The static factory method makes the code more concise when creating instances of parameterized types. scenario: Java's generic class, when instantiated, still needs to write two type parameters, which is very verbose. The static factory approach can help you improve this situation: for example, suppose you provide a static factory method in the HashMap class as follows:

 Public static <k, v= "" > Hashmap<k, v= "" > newinstance () {   returnnew Hashmap<k, v= "" >();  }

So, the call should look like this:

HASHMAP<STIRNG, list<string= "" >> m = hashmap.newinstance ();

In the case of parameterized constructors, it is often necessary to do so, which is cumbersome.

New Hashmap<string, list<string= "" >>

It is also worth mentioning that the static factory method returns the class to which the object belongs, and does not have to exist when writing the class that contains the static factory method. This flexible, static factory approach forms the basis of the service provider Framework (Provider framework), such as the JDBC API. The so-called service provider framework refers to a system in which multiple service providers implement the same service, and the framework, or system, is responsible for providing clients with multiple implementations of this service and decoupling those implementations. The service provider framework has three main components: 1. Service Interface (interface), which is implemented by the provider. 2. Provider Registration API (Provider Registration API), which is used by the system to register implementations that allow clients to access them. 3. Services Access API (service access API), which is used by clients to obtain service instances. There is also a fourth optional interface, service Provider Interface (Provider Interface), which is responsible for creating an instance of its service implementation. Without the service provider interface, the implementation is registered according to the class name and instantiated by reflection. For JDBC, connection is its service interface, Drivermanager.registerdriver is its provider registration api,drivermanager.getconnection is the service access Api,driver is the service provider interface.

As provided in two static factory methods empty and preallocate (meaning, reallocation; reassign) are used to create an empty object and a string object with the specified allocation space, respectively. In terms of usage, these static methods do provide a way for users to easily determine their role and application scenarios without having to search for each constructor and its argument list in a set of overloaded constructors to find the constructor that fits the current scene.

In terms of efficiency, because a unique static empty object is provided, when the interpretation object instance is empty (IsEmpty), the address of the prefabricated static empty object (Emptystring) is compared with the current object directly, and if it is the same address, the current instance is confirmed to be an empty object. For the Preallocate function, as the name implies, the function pre-allocates a specified size of memory space, and later, when using the string instance, you do not have to worry about assigning or appending too many characters to cause frequent realloc (re-allocating memory) operations. 2. It is not necessary to create a new object each time they are called. Or based on the code example above, since all the empty objects share the same static empty object, this also saves more memory overhead, and if the empty object is constructed by StrEmpty2, it will lead to more efficiency overhead when performing comparisons and other operations. In fact, Java in the implementation of the string object, using a constant resource pool is also based on the same optimization strategy. The same advantage applies to single-instance mode. 3. You can return any subtype of the original return type.in the Java Collections Framework's collection interface, a number of static methods are provided to return the implementation type of the collection interface type .such as Collections.sublist (), collections.unmodifiablelist () and so on. The interface returned is explicit, but for a specific implementation class, the user of the function does not need to know. This not only greatly reduces the number of exported classes, but in the future if it is found that the implementation of a sub-class is less efficient or to find a better data structure and algorithm to replace the current implementation of the subclass, for the user of the collection interface, there is no impact. This book, in the example, mentions that Enumset is returning an object instance through a static factory method, does not provide any constructors, and it internally provides an optimization when the implementation class is returned, that is, if the number of enumerations is less than 64, the factory method returns a specially optimized instance of the implementation class (Regularenumset ), which uses a long (64bits in Java) different bits to represent different enumeration values. If the number of enumerations is greater than 64, an array of long is used as the underlying support. However, the optimization of these internal implementation classes is transparent to the user. 4. When creating instances of parameterized types, they make the code more concise. map<string,string> m = new hashmap<string,string> (); Because Java cannot be inferred from a type in a call to a constructor, it is not possible to instantiate an instantiated object of the specified type parameter through the constructor's parameter type. However, the static factory method can take advantage of the parameter type deduction, avoiding the worry of the type parameter being rewritten multiple times in a declaration, see the following code:

Just five minutes to finish reading effective Java

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.