"Effective Java" learning notes (1)

xiaoxiao2021-03-05  21

This book is like "Effective C " as the meaning of "Effective C ", I think it is one of every Java enthusiast, recently, and some study notes hope. Can help everyone.

One. Create and destroy objects

First: Consider replacing the constructor with a static factory method

Instance code: Valueof () method in the Boolean class

Public Static Boolean Valueof (Boolean B)

{

RETURN (B? Boolean.true: boolean.false);

}

advantage:

1. Unlike constructor, static factory methods have their own name. If there is a variety of constructor, some are only the same as the parameter, and you should consider the use of static factory methods.

2. Static factory methods are not required to create an object. A pre-constructed object can be used. For example, the boolean.valueof () method will never create an object. In the case of frequent creation of objects, and if you create a high cost, you should consider adopting a static factory method.

3. Unlike constructor, the static factory method can return an object of a sub-type of the original returns. The best example in this regard is Collectes framework. Collections framework has 20 practical set interface implementations, most of which are exported by a static factory method in java.utl.collections.

Disadvantages:

1. If a class does not contain public or protected constructors, it cannot be inherited. In a sense, this also limits the abuse of inheritance.

2. The static factory method is the same as other static methods, and it is generally necessary to make a special instructions in the API documentation. You should use the specification constructor without strong needs.

Article 2: Use a private constructor to enhance the Singleton attribute

The so-called Singleton refers to such a class, which can only be instantiated / (that is, single case mode), there are two ways, as follows:

1. Provide a static constant

Public class example {

Public static final example instance = new example ();

Private example () {// Constructor is private

...}

....

}

2. Use static factory method

Public class example {

Private static final example instance = new example (); // change to private

Private example () {// Constructor is private

...}

Public static example getInstance () {

Return Instance;

}

....

}

The first method may be better in performance, and the second method provides greater flexibility, you can decide whether to make Singleton. To make a class of Singleton become sequentially, it is not enough to implement the Serializable interface, and a readResolve () method must be provided, otherwise a new instance will be generated. Violation of Singleton's intention

Private Object Readresolve () THROWS ObjectStreamException {

Return Instance;

}

Article 3. Enhanced unampleable capabilities through private constructor

That is, it is not possible to generate any object. Or do you want to write an abstract class? NO, abstract class can be implemented, and its subclass can also be implemented. What we want is definitely unsearched, this class typically only has some static variables and static methods, just use as a tool class, such as java.utl.arrays. To do this, just contain a private explicit constructor. This also guarantees that this class cannot be inherited because the subclass cannot access the constructor of the parent class. Article 4: Avoid repeating the creation of objects

If an object is non-variable, it can always be reused instead of creating an object. E.g

String s = new string ("DENNY");

"Denny" itself is an example. And this sentence re-creates an same instance each time. This is completely unnecessary, and if such a statement is used in a frequently called method, there will be a big impact. Should

String s = "DENNY"; instead of the above statement. A common method is to make the object you need to use into a private static constant (of course, to ensure that these variables will no longer change after the creation), with a Static block contains them. In addition, don't think that the cost is very expensive. Instead, some small object constructor often only do very little work, so the creation of small objects is very cheap, only the heavyweight objects (such as database connections) need to be used Object pool reuses objects.

Article 5: Eliminate expiration reference

"Memory leak"! What, I have something wrong, Java also has "memory leak". Yes, that is not a patent of C . See the example below

Public class stack {

PRIVATE OBJECT [] Elements;

PRIVATE IN SIZE = 0;

Public stack (int initialcapacity) {

This.elements = new object [InitialCapacity];

}

Public Object Pop ()

{

IF (size == 0)

Throw new emptystackexception ();

Return Elements [- size];

}

....

} This program does not have a significant error, but with the increasing memory occupation, the performance of the program will gradually appear. The reason is that when this stack shrinks, the object popned from the stack will not be treated as garbage, because the stack maintains the expiration reference of these objects, which will never be released again, should POP operation modification:

Public Object Pop ()

{

IF (size == 0)

Throw new emptystackexception ();

Object result = elements [- size];

Elements [size] == null; // Set the reference to NULL

Return Result;

}

I have such problems in the class that manages memory, and I have to be vigilant. Another source of memory leaks is cache, you caught an object, but forgot to release. Memory leak issues can be detected by specialized tools.

Article 6: Avoid using the end function (femance ())

I think of when I have different in the 9CBS forum, someone should use FinLize (), and C , I actually reply to handle some operations to close the resource in the Finalize () method (turn off files, etc.). Sweat! The end function does not guarantee that it will be executed in time, from an object change, it is not reachable (reference to this object through the object network), to its end function is executed, the length of this time is arbitrary, uncertain . Therefore, time-critical tasks should not be completed by the end function, such as turning off a file that has been opened. Since the JVM delay performs the end function, a large number of files remain open! Moreover, the implementation of the end function is different from different JVMs, so you can't guarantee the portability of this function. Remember this: We should not rely on a terminator to update the key permanent state.

So how do we program to perform cleanup work, usually provide an explicit termination method, usually in combination with Tr..finally structures, the example of this is the various stream operations in java.io, basically There is a close () method, you must explicitly close the open resource. There are two reasonable aspects of the use of end functions:

1. When serving as the last "safety net", when the client is forgotten or cannot invoke the explicit termination method.

2. When calling a local object, the local object does not have a critical resource, and the termination method completes the necessary work to release resources.

转载请注明原文地址:https://www.9cbs.com/read-38240.html

New Post(0)