effictive Java Learning Note 1: Creating and destroying objects

Source: Internet
Author: User

Recommendation 1: Consider replacing the constructor with a static factory method

Reasons: 1) static method has a name ah, easier to understand and understand. Construction method overloading is confusing, not a good idea.

2) The static factory method does not have to create a new object each time it is called, and the public constructor creates an object instance each time the call is made. You can create objects beforehand so that you can avoid creating non-repeatable objects.

The static factory method can return the same object for repeated calls.

Cons: If the class does not have a constructor, it cannot be quilt-like, the subclass of super () can not be used

Recommendation 2: When multiple constructor parameters are encountered, consider using the builder

Reason: Overlapping constructor form, constructor overloading.

When you encounter many constructor parameters, you can use the JavaBean mode. In this mode, a parameterless constructor is called and the setter is called to set each necessary parameter and the associated optional parameters.

But the Java bean pattern has a fatal problem because the bean thread is unsafe and state inconsistent because it takes a lot of steps to create the bean. Requires the programmer to pay extra to keep him thread safe.

Third Kind

effictive Java Learning Note 1: Creating and destroying objects

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.