Item 1 Consider static factory method instead of constructors
Advantages:
- One advantage of static factory methods is that, unlike constructors, they have names. (Mostly used in Java.utils.Collections)
- 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.
- 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)
- A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.(可以通过为具有泛型参数的类提供static factory method来消除实例化该类时的泛型参数)
Disadvantages:
- 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)
- 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.
本文探讨了静态工厂方法相较于构造函数的优势与劣势,并强调了在某些情况下使用静态工厂方法的重要性,特别是在避免直接创建对象时。
1309

被折叠的 条评论
为什么被折叠?



