Effective Java Reading Notes

Chapter 2 Creating and Destroying Objects

Item 1: Use static factory methods instead of constructors

Five advantages of static factory methods:

  1. they have names;
  2. No need to create a new object every time they are called;
  3. Any subtype object of the original return type can be returned;
  4. The class of the returned object can change with each call, depending on the parameter values ​​​​of the static factory method;
  5. The class of the object returned by the method may not exist when writing the class containing the Jingtai project method; (the
    Service Provider Framework is formed, and there are three important components in the Service Provider Framework: Service Interface (Service Interface) Interface), provider registration API (Provider Registration API), service access API (Service Access API))

Two major disadvantages of static factory methods:

  1. A class cannot be subclassed if it does not have a public or protected constructor;
  2. It is difficult for programmers to find them;
    list some customary names of static factory methods:
    from - type conversion method
    of - aggregation method
    valueOf
    instance or getInstance
    create or newInstance
    getType
    newType
    type
Item 2: Consider using a builder when you have multiple constructor arguments
Builder模式灵活,使构造器动态化(模拟了具名的可选参数)
Builder模式可能存在性能问题
Item 3: Enforce Singleton Properties with Private Constructors or Enum Types
Item 4: Enforce non-instantiable capabilities with private constructors
public class UtilityClass{
    
    
	private UtilityClass{
    
    
    	throw new AssertionError();	//保证该类在任何情况下都不可以被实例化
    }
}
Item 5: Prioritize dependency injection to reference resources
Item 6: Avoid creating unnecessary objects

For objects that provide both a static factory and a constructor, the static factory is preferred. The constructor will create the object multiple times, and the object created by the static factory can be reused (when the content of the object does not need to be changed).

Item 7: Eliminate expired object references

Three situations that lead to memory leaks:
1. Objects popped from the stack will not be treated as garbage collection, because these expired references are maintained inside the stack: once they are not used, just clear the objects; 2. The
cache is easy to be forgotten: use WeakHashMap Instead of caching, the cache should regularly clear useless items (LinkedHashMap);
3. Listeners and other callbacks: the best way to cancel callbacks after registering callbacks, and ensure that callbacks are garbage collected immediately is to only save their weak references (weakreference ), for example, only save them as keys in WeakHashMap;

Item 8: Avoid Finalizers and Cleaners
Item 9: Prefer try-with-resources over try-catch

Chapter 3 Methods Common to All Objects

Guess you like

Origin blog.csdn.net/qq_16253859/article/details/118884994