Static factory method compared to the constructor of the pros and cons

  1. What is a static factory method?
    Examples of commonly employed we have obtained class is new, by obtaining an instance constructor. In addition, we can use a static method to provide their own examples of external, namely static factory methods.

  2. Advantage of static factory method

    2.1 static factory method can have its own name
    constructor and the class of the same name, when multiple overloaded constructor appears only difference in the parameter list, the user is easy to confuse. The static factory method may be different for different parameter list defined name, highlight the differences between the different static factory method.

    Creates 2.2 does not have to call every time a new object
    and sometimes external callers only need to get one instance, does not care whether the new instance; or if we want to provide a single example when outside - if you use the factory method, you can easily in internal control, prevent the creation of unnecessary objects, reduce overhead.

    2.3 may return to the original return type of a subclass
    which gives us greater flexibility in the choice of the returned object class. Especially For interface-based framework, can have a static method after Java8 interfaces, then we can refer to the object to be returned directly through the interface.

    2.4 Class returned object may change with each call changes
    the value of return different results depending on various parameters, as long as the return type of the subclass can be declared, the specific implementation process is not visible. This allows developers to follow-up on the implementation class can be modified without causing negative consequences.

    2.5 method returns the object's class, the static method in the preparation may be absent.
    This flexible features constitute the basis for the service provider framework.

  3. The disadvantage of static factory method
    , if a class does not contain a public or protected constructor can not be subclassed. In addition, compared to the constructors, static factory method is not clearly identified in the API documentation, it can not easily be perceived by the programmer.

发布了15 篇原创文章 · 获赞 0 · 访问量 442

Guess you like

Origin blog.csdn.net/hblack_313/article/details/104039582