반응형
2. Creating and Destroying Objects
- when and how to create objects
- how to ensure they are destroyed in a timely manner
- how to manage any cleanup action that must precede their destruction
-
Consider static factory methods instead of constructors
public static Boolean valueOf(boolean b){ return b? Boolean.TRUE : Boolean.FALSE; }
-
A static factory method is not the same as the Factory Method Pattern from Design Patterns
-
Providing static factory methods has both advantages and disadvantages.
<Advantages>
- Static factory methods have names - a static factory with a well0chosen name is easier to use and the resulting client code easier to read
- Static factory methods are not required to create a new object each time they're invoked
- They can return an object of any subtype of their return type
- The class of the returned objects can vary from call to call as a function of the input parameters.
- The class of the returned objects need not exist when the class containing the method is written.
<Disadvantages>
- Classes without public or protected constructors cannot be subclassed
- They are hard for programmers to find.
- Common names for static factory methods
- from
- of
- valueOf
- instance or getInstance
- create or newInstance
- getType
- newType
- type
- Common names for static factory methods
-
-
Consider a builder when faced with many constructor parameters
- Telescoping constructor pattern → It is hard to write client code when there are many parameters, and harder still to read it.
- JavaBeans Pattern → allows inconsistency, mandates mutability / this pattern precludes the possibility of making a class immutable and requires added effort on the part of the programmer to ensure thread safety.
- Builder Pattern → well suited to class hierarchies. the safety of telescoping constructor pattern + the readability of the JavaBeans pattern / you must first create its builder → it could be a problem in performance-critical situations.
-
Enforce the singleton property with a private constructor or an enum type
- Making a class a singleton can make it difficult to test its clients → it's impossible to substitute a mock implementation for a singleton useless it implements an interface that serves as its type.
- the public field approach(preferable) - the API makes it clear that the class is a singleton - the public static filed is final, So it will always contain the same object reference.
- The static factory approach - it gives you the flexibility to change your mind about whether the class is a singleton without changing its API. a method reference can be used as a supplier
- A single-element enum type is often the best way to implement a singleton
반응형