Consider replacing the constructor with a static factory method
The static factory method here refers to a method in a class that uses the public static modifier, and does not have any relation to the factory method pattern of the design pattern. The static factory approach has several advantages over creating objects with a common constructor:
1, the static factory method has the name: through the meaningful static factory method name can well express the function of the factory method, easy to distinguish the function similar multiple static factory method.
2. Static factory methods can have more complex production object logic, not just a new object: You can either create a new object or use a cached object.
3. The static factory method can return an object of any subtype of the original return type: Because the interface cannot have static methods, the static factory method of the interface type is typically placed in a tool class named types.
4. Static factory methods When you create a parameterized type instance, the code is more concise: Use the type derivation mechanism.
The static factory approach also has all the drawbacks:
1, if the class only provides a static factory method and does not provide public or protected constructor, it will cause the class can not be quilt class.
2, the public static factory method is essentially a common static factory method, the Java specification does not treat him in special.
Extension: The static factory method has some idiomatic names:
1. valueof--type Conversion method
2. of--type Conversion method
3. getinstance--use parameters to describe the returned instance
4. newinstance--use parameters to describe the returned instance, each time returning a new instance
5. Gettype--type represents the type of the returned object
6. Newtype--type represents the type of the returned object, each time it returns a new type
Thinking: The static factory method in Java specification, is the ordinary class method, in the role and use of more space to change. The constructor is specially treated by the Java language, and the function and function of the constructor are also regulated by the Java language Specification. The four advantages listed above and two shortcomings are derived from the difference between the two.
Second, when encountering multiple constructor parameters, consider using the builder
Static factory methods and constructors have a common limitation: they do not scale well to a large number of optional parameters. When a class contains more than one domain and there are optional domains, the workaround is:
1. Overlapping constructor mode: the first constructor contains only the required parameters, and the subsequent constructors add an optional parameter at a time. Cons: Difficult to use and read.
2. JavaBeans mode: Use the parameterless constructor to create the object, call the setter method to set the necessary parameters and optional parameters. Cons: Tedious steps, inconsistent state.
3, builder mode: Use the necessary parameters to get a Builder object, call the Builder object setter method, call the non-parameter build method to produce immutable objects. Cons: Poor performance, lengthy calls.
Thinking: Three ways each have their own advantages and disadvantages: The overlapping constructor mode logic is simple, easy to grasp, JavaBeans mode is less used, and is not recommended, builder mode is suitable for many parameters and optional parameters.
Third, using a private constructor or enumeration type to harden the Singleton property
As long as it is a class of Singleton, its constructor must be private. For singleton classes, all instance fields must be transient and provide a readresolve method to make them serializable correctly.
Thinking: Single-Element enumeration types are the best way to implement Singleton. Provides a serialization mechanism for free, and absolutely prevents multiple instantiations.
Iv. ability to harden non-instancing through private constructors
It is not feasible to force a class to be instantiated by making it an abstract class. By inheriting the class, subclasses can be instantiated, thereby instantiating the class. Doing so is a false use of the abstract class and misleading the user. Abstract classes should be designed for inheritance only. The best solution is to provide a private constructor for the reality, which also makes the class not quilt-like.
Thinking: After determining the function of the class, try to minimize the permissions of the constructor of the class.
V. Avoid creating unnecessary objects
1. The constructor creates a new object each time it is called, and the static factory method never requires it. Use static factory methods as much as possible.
2. In addition to reusing objects of immutable classes, you can reuse mutable class objects that are known not to be modified.
3. A specific adapter for a given object does not need to create multiple adapter instances. For example, the keyset method of the Map interface returns the same set view each time.
4, after introducing the automatic unpacking and boxing function in Java1.5, we should pay attention to using basic type instead of reference type, and pay attention to the automatic boxing of the unconscious.
5, the creation and recycling of small objects is very inexpensive, if for the sake of clarity, simplicity and functionality of the program, you can not avoid the creation of objects. Maintaining your own object pool is a good practice only if the object is a weight level.
Vi. elimination of expired object references
1. Emptying an object reference is an exception, not a canonical behavior. Defining each variable within the most compact scope is a good programming norm.
2, as long as the class is their own management of memory, programmers should be wary of memory leaks.
3. Caching is another common source of memory leaks. Weakhashmap the lifetime of the cache entry is determined by the external reference of the key and not by the value.
4. A third common source of memory leaks is listeners and other callbacks. This problem can be resolved by saving the listener and other callbacks for the weak application (weak reference).
5, the memory leak problem is generally more covert, need to carefully review the code, combined with the heap profiling tool to discover the problem of memory leaks.
Vii. avoiding the use of termination methods
1. The End method (finalizer) is often unpredictable, dangerous, and unnecessary.
2, disadvantage one: can not be guaranteed to be implemented in a timely manner. Different JVMs have large differences in performance. The thread that executes the method is not deterministic. The Java specification does not guarantee that the finalization method will be executed.
3, the shortcomings of the second: The exception is not caught in the end method of the strange behavior, destroying the state of the object, making the finalization method more dangerous.
4, disadvantage three: The End method has a very serious loss of performance.
If the resource encapsulated in the object of the class does need to be terminated, you can provide a terminating method that is displayed. It is used in conjunction with the try-finally structure to ensure timely termination. Refer to the Close method for each stream object. The disadvantage of terminating a method is that it requires the programmer to display the call itself. In contrast, the summary method also has two benefits:
1. Acting as a "safety net" is the last opportunity for releasing resources. You can increase the logging in it, prompting the next step to fix the bug.
2. Can be used to release local peers that do not have critical resources.
Note: The finalization method chain is not automatically executed, and you need to call the parent class's finalization method in the subclass. You can resolve this issue through the "End method Guardian" mode.
Think: Do not use the finalization method unless you are a safety net, or if you want to terminate non-critical local resources.
Effective one of the Java reading notes Create and Destroy objects