"Reading notes-effective Java" 01. Consider replacing constructors with static factory methods

Source: Internet
Author: User
Tags protected constructor

There are two ways to get an instance of a class:

1. Provide a public constructor (most commonly used).

2. Provide a public static factory method (static factory methods).

// Static Factory Method Example  Public Static Boolean ValueOf (boolean  b) {    return b?  Boolean.TRUE:Boolean.FALSE;}

Advantages of the Static factory approach:

1. There is a name. When a class requires more than one constructor with the same signature (method signature = method name + parameter list), the static factory method is used instead of the constructor, and the name is carefully chosen to highlight the difference between them.

2. You do not have to create a new object each time you call them.

3. You can return an object of any subtype of the original return type.

4. Make your code more concise when you create a parameterized type instance. Type deduction: For example, K and V in hashmap<k,v> are parameters, and if the parameters are more than one, each time new is written again, it looks lengthy.

Disadvantages of the static factory approach:

1. If the class does not contain a public or protected constructor, it cannot be quilt-like.

2. There is virtually no difference from other static methods.

Extracurricular Links: service provider Framework . There are three important components:

1.Service Interface: Provider Implementation.

2.Provider Registration API: What Provider are registered.

3.Service Access API: Invokes the Service of provider.

An optional component: Service Provider Interface.

Detailed: 7227197

"Reading notes-effective Java" 01. Consider replacing constructors with static factory methods

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.