Think in Java static Factory method Learning Summary

Source: Internet
Author: User

A static factory method is a static method that returns an instance of a class. Static factory methods are used instead of construction methods.

1. Advantages of static Factory method

If a constructor parameter does not specifically describe the object to be returned, then a static factory method using a meaningful name makes the class more useful.

If a class has multiple construction methods with the same characteristics, then a static factory method with a special meaning name should be considered instead of a construction method.

Static factory methods do not require a class object at the time of invocation. For a non-mutable class, you can use a pre-constructed instance, or the instance is already cached to avoid creating duplicate objects.

A static factory method can return the same object for repeated calls. First he can make sure that a class is a singleton; second he makes the non-mutable class does not exist two equal instances (= = and eques are true). using = = instead of eques can improve performance.

A static factory method can return a subclass object of a class. The implementation returns a non-public class, hiding the concrete implementation, and the API is more concise.

Interface as the natural return type of a static factory method.


2, the lack of static factory methods

Classes cannot be quilt-like if they do not contain public or protected class construction methods.

Common valueof getinstance

3. Summary

The construction method conforms to the specification and is used preferentially.

Think in Java static Factory method Learning Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.