"Effective Java reading notes" Creating and destroying Objects (i): Consider using static factory methods instead of constructors

Source: Internet
Author: User

Class can provide a static method that returns a static instance of a class, such as a static method that obtains an instance of a Boolean wrapper class

1  Public Static Boolean ValueOf (boolean  b) {2        return (b?  True:false); 3    }

Advantages:

1, there is a name. When a class requires more than one constructor with the same signature, the static factory method is used instead of the constructor, and the name is carefully chosen to highlight the difference between them. such as: biginteger.probableprime (int bitlength, random rnd) returns a random prime number.

2, you do not have to create a new object each time they are called.

3. It is possible to return its subclasses, with greater flexibility in choosing the class that returns the object.

4, simplify the code.

Disadvantages:

1, the whole class if there is no public or protected type of the constructor, it will not be inherited, that is, not as a superclass, equivalent to final.

2, unlike other static methods in the API documentation is not different, unlike the constructor can be identified in the API

Static Factory method Customary name:

    • The instance returned by valueof--has the same value as its parameter, which is actually a type conversion method
    • Of--valueof Simple alternative, enumset in use
    • GetInstance
    • newinstance--with getinstance to ensure that each returned instance is different from other instances
    • Gettype--type indicates the type of object returned by the factory method
    • NewType

"Effective Java reading notes" Creating and destroying Objects (i): Consider using static factory methods instead of constructors

Related Article

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.