"Regain effective Java" one

Source: Internet
Author: User
Tags protected constructor

Before reading this book "Effective Java (second edition)" is very early. This book is indeed a good book. You need to chew slowly and have a different experience every time you look.

Write a blog here to consolidate.

Chapter I. Creating and Destroying objects

Consider replacing the constructor with a static factory method

Usually we get an instance of the class, and the more frequently used method is to use the constructor. And here is the use of the public static Factory method (Note: The factory method pattern in the static factory method and design pattern is not allowed to think)

  • The first advantage of static factory methods differs from constructors is that they have names. Assuming that the constructor's parameters do not have an exact description of the object being returned, the static factory with the name will be easier to use and the code will be easier to understand. A class can only have a constructor with a specified signature, and of course we can make multiple constructors with different parameters, but the trouble is to make the code more complicated or not to remember. The static method has a name. So there is no limit.

  • The static factory method does not have to create a new object each time it is called. The static factory method can return the same object for repeated calls. This helps the class to always tightly control which instances should exist at some point, and this class is called an instance-controlled class.
  • A static factory method can return an object of whatever subtype of the original return type.

    The class of the object returned by the public static factory method can not only be non-public, and the class can also change with each invocation, depending on the value of the static factory. Only the subtype of the returned type that has been declared is agreed.

    The static factory method returns the class to which the object belongs, and the class that is written to include the static factory method does not have to exist. This flexible, static factory approach forms the basis of the service provider framework. Service Provider framework: Multiple service providers implement a service, and the system provides multiple implementations for the client of the service provider. and decoupling them from multiple implementations. There are three important primary keys in the service provider framework: The service interface, which is a provider internship. Provider Registration API. This is the system used to implement the registration, in order for the client to visit them, the service access API. Is the instance that the client uses to obtain the service. The Service access API generally agrees but does not require the client to specify a condition for a provider. Assuming there is no such provision, the API returns an instance of the default implementation. The Service access API is a "flexible static factory" that forms the basis of the service provider framework.

    The fourth interface of a service provider is optional, the service provider interface, which is responsible for creating instances of its service implementations.

    Assume there is no service provider interface. The implementation is registered according to the class name and is instantiated by means of reflection.

  • The static factory method is used when creating an instance of a parameter type. The code is more concise, such as the following piece of code:
    Map<string. list<string>>  map=  new hashmap<string,list<string>> ();//This is more troublesome than   <pre name= " Code "class=" Java >//assumes HashMap provides this static factory: public static <K,V> hashmap<k,v> newinstance () {           return New hashmap<k,v> ();} Then we can write it that way. For example the following map<string,list<string>> map=hashmap.neweinstance ();
  • Disadvantages of the static factory approach: The class hypothesis does not contain a public or protected constructor. Can not be quilt-like, for the public static factory returned by the non-public class. It is also true.
  • Disadvantages of static factory methods: They are virtually no different from other static methods.

Consider using the builder when you encounter multiple constructor parameters

Static factories and constructors have limitations and cannot be extended very well to a large number of optional parameters. Usually we get used to overlapping constructors.

Public A (Int. A,int b) {this   . A (a,b,1);} Public A (int a,int b,int c) {     ///////}
We can find out. Overlapping constructors are possible. It's complicated when you're dealing with multiple parameters. Then we're going to use the JavaBeans mode.

public int a=0;public int B=0;public int C=0;public A () {public   void Seta (int a) {this.a=a;} public void Setb (int b) {this.b=b;} public void setc (int c) {This.c=c}}
This makes up for the complicated shortcomings of the overlapping constructors.

It's just that. The JavaBeans itself is flawed. Because the construction process is cut into several calls, the JavaBeans may be in an inconsistent state during construction, and the class cannot maintain consistency only by verifying the validity of the constructor parameters. A view that uses an object that is in an inconsistent state will cause a failure.


Hardening the Singleton property with a private constructor or enumeration type

Singleton refers to classes that are instantiated only once, and Singleton are often used to represent system components that are inherently unique.

Ability to harden non-instancing through private constructors

Sometimes we need to write a class that includes only static and static fields, and often we need to use the method in Java.lang.Math, which is called this.

Avoid creating unnecessary objects

It is often better to reuse objects instead of creating new objects of the same functionality each time they are needed, for immutable classes that provide static factory methods and constructors at the same time, and are often able to use static factory methods instead of constructors to avoid creating unnecessary objects. It is not a good practice to avoid creating objects by maintaining the object pool, unless the objects in the pool are non-heavyweight.

The typical use of object pooling is the database link pool, the cost of establishing database links is very expensive, so it is necessary to reuse these objects.

Elimination of expired object references

The best way to eliminate outdated references is to have the variables that contain the reference end their lifecycle. The assumption is that each variable is defined in the most compact scope, and this happens. In general, we should be wary of memory leaks if we manage memory, and once the elements are released, whatever object references that are included in the element should be emptied.

A common source cache for memory leaks. Once you put the object's reference in the cache, it's very easy to forget.

A memory leak also has a source listener and other callbacks, assuming you implement a api,client callback in this API. Without a display to cancel the registration, then unless you take certain actions. Otherwise it will accumulate. The solution is to simply save their weak references.

"Regain effective Java" one

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.