`
leonzhx
  • 浏览: 791677 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 1: Consider static factory methods instead of constructors

阅读更多

1.  One advantage of static factory methods is that, unlike constructors, they have names. BigInteger(int, int, Random), which returns a BigInteger that is probably prime, would have been better expressed as a static factory method named BigInteger.probablePrime. In cases where a class seems to require multiple constructors with the same signature, replace the constructors with static factory methods and carefully chosen names to highlight their differences.

 

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. This allows immutable classes to use preconstructed instances, or to cache instances as they’re constructed, and dispense them repeatedly to avoid creating unnecessary duplicate objects.

 

3.   A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. One application of this flexibility is that an API can return objects implementing certain interface without making their implementation classes public. Interfaces can’t have static methods, so by convention, static factory methods for an interface named Type are put in a noninstantiable class named Types.(Collections have static methods returning unmodifiable , synchronized implementations of Collection without disclose their implementations) The class of the returned object can also vary from release to release for enhanced software maintainability and performance.

 

4.   The class java.util.EnumSet has no public constructors, only static factories. They return one of two implementations, depending on the size of the underlying enum type: if it has sixty-four or fewer elements, as most enum types do, the static factories return a RegularEnumSet instance, which is backed by a single long; if the enum type has sixty-five or more elements, the factories return a JumboEnumSet instance, backed by a long array.

 

5.   The class of the object returned by a static factory method need not even exist at the time the class containing the method is written. Such flexible static factory methods form the basis of service provider frameworks, such as the Java Database Connectivity API (JDBC).

 

6.   A service provider framework is a system in which multiple service providers implement a service, and the system makes the implementations available to its clients, decoupling them from the implementations. There are three essential components of a service provider framework: a service interface, which providers implement; a provider registration API, which the system uses to register implementations, giving clients access to them; and a service access API, which clients use to obtain an instance of the service. An optional fourth component is a service provider interface, which providers implement to create instances of their service implementation. In the absence of a service provider interface, implementations are registered by class name and instantiated reflectively.( In the case of JDBC, Connection plays the part of the service interface, DriverManager.registerDriver is the provider registration API, DriverManager.getConnection is the service access API, and Driver is the service provider interface.)

 

7.   A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances. By type inference , you could replace the wordy declaration: 

Map<String, List<String>> m = new HashMap<String, List<String>>();

 with the following succinct:  

Map<String, List<String>> m = HashMap.newInstance();

 If HashMap have the following static method : 

public static <K, V> HashMap<K, V> newInstance() {
    return new HashMap<K, V>();
}

 However Java 7 has already support the following syntax: 

Map<String, List<String>> m = new HashMap<>();

 

8.   The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.

 

9.   A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.

 

10.  common naming conventions for static factory methods:

    a)  valueOf—Returns an instance that has, loosely speaking, the same value as its parameters. Such static factories are effectively type-conversion methods.
    b)  of—A concise alternative to valueOf, popularized by EnumSet.
    c)  getInstance—Returns an instance that is described by the parameters but cannot be said to have the same value.
    d)  newInstance—Like getInstance, except that newInstance guarantees that each instance returned is distinct from all others.
    e)  getType—Like getInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.
    f)  newType—Like newInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 1: Consider static factory methods instead of constructors Item 2: Consider a builder when faced with many constructor parameters Item 3: Enforce the singleton property with a private constructor...

    effectice_java第二版 英文

    2. **条目2:考虑为静态工厂方法而不是构造器(Consider Static Factory Methods Instead of Constructors)** 静态工厂方法有命名灵活性,不需创建新类就能返回实例,还可以返回原类型的子类型,或者在不需要时...

    Building Maintainable Software, Java Edition(O'Reilly,2016)

    Write short units of code: limit the length of methods and constructors Write simple units of code: limit the number of branch points per method Write code once, rather than risk copying buggy code ...

    Building Maintainable Software, C# Edition [2016]

    Write short units of code: limit the length of methods and constructors Write simple units of code: limit the number of branch points per method Write code once, rather than risk copying buggy code ...

    jmockit测试例子

    1. If the static methods invoke only happens in few classes, we could create an adaptor to isolate them. The implementation of adaptor is just simply delegation. 2. Unfortunately, sometimes your ...

    C++_CLI标准.pdf

    - **Static Constructors**: Section 8.8.9 covers static constructors in ref classes. - **Inheritance**: Section 8.8.10 discusses inheritance in ref classes. - **Value Classes**: Section 8.9 provides ...

    PowerMock资料大全(E文)

    PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more....

    effective_java_new:Effective_java_new

    7. **优先考虑静态工厂方法(Consider Static Factory Methods Instead of Constructors)**:静态工厂方法比构造器更灵活,不强制创建新的类实例,可以返回类的子类实例,或者在没有合适构造器时提供默认实现。...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Classes Doing Work in Constructors Default Constructors Explicit Constructors Copy Constructors Structs vs. Classes Inheritance Multiple Inheritance Interfaces Operator Overloading Access Control ...

    SpringSource CoreSpring认证考试题库.docx

    题目:Consider the following code sample which creates an ApplicationContext from a file called "application-config.xml" in the "rewards.internal" package, and a file called test-infra-config.xml in ...

    c++ Strings

    Instead, strings in C are typically represented as arrays of characters terminated by a null character (`\0`). While this approach works, it lacks the convenience and functionality found in other ...

    Copy Constructors and Assignment Operators终极解释

    在C++编程语言中,复制构造函数(Copy Constructor)和赋值运算符(Assignment Operator)是两个非常关键的概念,特别是在处理对象的拷贝和赋值时。它们默认由编译器提供,但通常需要根据具体需求进行自定义,以确保正确...

    Addison.Wesley.C++.by.Dissection.2002.pdf

    ### Chapter 1: Writing an ANSI C++ Program This chapter introduces the reader to the fundamentals of writing a C++ program. It covers: - **Getting Ready to Program:** Discusses the setup required to ...

    Google C++ Style Guide_英文版.pdf

    Static member functions can be useful in certain contexts, such as factory methods. #### Classes - **Doing Work in Constructors:** Constructors should perform only initialization and not complex ...

    C 程序设计教学课件:Chapter 3 class and object.ppt

    Static member functions, also known as class methods, can be called without creating an instance of the class. They don't have access to non-static data members directly. Constants are used to ...

    软件需求分析英文课件

    Variables, methods, and constructors Association Aggregation and composition Generalization and inheritance Abstract class Interface © Pearson Education 2007 Appendix (Maciaszek - ...

    Java反编译软件JAD1

    -t - use tabs instead of spaces for indentation -t&lt;num&gt; - use &lt;num&gt; spaces for indentation (default: 4) -v - display method names being decompiled -8 - convert UNICODE strings into 8-bit strings ...

    methods-this-constructors

    设定说明通过npm install -g jasmine安装 。 然后派生并克隆此存储库。如何使用cd进入克隆此存储库的fork的目录,然后键入jasmine 。 建议您按字母顺序尝试这两个问题。

    Beginning PHP 5.3

    - **Constructors and Destructors:** Discussion on constructors and destructors, including automatic instantiation and cleanup of objects. #### Part III: Using PHP in Practice **Chapter 9: Handling ...

    A tiny JSON library for C++11.

    There are also helper methods Json::dump, to serialize a Json to a string, and Json::parse (static) to parse a std::string as a Json object. It's easy to make a JSON object with C++11's new ...

Global site tag (gtag.js) - Google Analytics