Effective Java notes-Creating and Destroying Objects(1)

Item 1 Consider static factory method instead of constructors

Advantages:

  1. One advantage of static factory methods is that, unlike constructors, they have names. (Mostly used in Java.utils.Collections)
  2. A second advantage of static factory methods is that, unlike constructors,they are not required to create a new object each time they're invoked.
  3. A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. (See service provider framework , eg : The JDBC Driver Manager)
  4. A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.(可以通过为具有泛型参数的类提供static factory method来消除实例化该类时的泛型参数)

Disadvantages:

  1. The main disadvantage of providing only static factory method is that classes without public or protected constructors cannot be subcalssed. (See Collections Framework, encourages progammers to use composition instead of inheritance)
  2. A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods. (In my point, this issue could be ignored, just seeking for an appropriate name for the method is ok)

 Key points of item1:

  • The static factory methods descriped in item1 has no direct equivalent in Design Patterns.
  • Avoid the reflex to provide public constructors without first considering static factories.

猜你喜欢

转载自whywjf.iteye.com/blog/2033502