Please enable JavaScript.
Coggle requires JavaScript to display documents.
Effective Java (Creating and Destroying objects (Builder when faced with…
Effective Java
Creating and Destroying objects
Static factory instead of constructor
: :checkered_flag:
Builder when faced with many constructor
:checkered_flag:
Telescoping constructor
Works, but it is hard to write client code when there are many parameters and harder still to read it
Javabeans pattern
May be in an inconsistent state partway
Builder pattern
call a constructor with all of the required parameters and gets a builder object
call setters-like methods on the builder object to set each optional parameter of interest
call a parameterless build method to generate the object, which is immutable
Enforce the singleton property
:checkered_flag:
Using public static final
private the constructor
Using factory (instance returning public method)
private the constructor
Using enum property
Enforce noninstantialbility with private constructor :checkered_flag:
Usually use for utility classes
Cannot use abstract class to define
Let the constructor be private :lock:
Avoid creating unnecessary objects :checkered_flag:
Can use static factory method to get instance
Eliminate obsolate object references
:checkered_flag:
Avoid finalizers :checkered_flag:
Methods Common to All Objects
equals, hashCode, toString, clone, finalize
Obey the general contract when overriding
equals
:red_flag:
Each instance of the class is inherently unique
You dont care whether the class provides a
logical equality
test
A superclass has already overridden equals, and the superclass behavior is appropriate for this class
Always override
hashCode
when you override
equals
:red_flag:
Always override
toString
:red_flag:
providing a good
toString
implementation makes your class much more pleasant to use
provide programmatic access to all of the information contained in the value returned by toString
when practical toString method should return all of the interesting information contained in the object
Consider implementing
Comparable
:red_flag:
Methods Common to All Objects