search
HomeJavajavaTutorialDetailed explanation of the use of static factory methods in Java

This article mainly introduces the relevant information about the detailed explanation of Java static factory methods. I hope that through this article, everyone can master the Java factory methods today. Friends in need can refer to

Java static factory methods Detailed explanation of examples

What is a static factory method

For a class, in order to allow users to obtain an instance of itself, the most commonly used The best way is to provide a public constructor.
Of course, what we want to introduce here is another method-static factory method, a static method that returns an instance of a class.
For example, a Boolean method that converts the basic type boolean into an encapsulated class, valueOf:


public static Boolean valueOf(boolean b) { 
  return (b ? TRUE : FALSE); 
}

Why use a static factory Method

So, why do we use static factory methods instead of constructors?

Because the static factory method has the following three characteristics-named, environmentally friendly, and multiple children, let’s talk about each one below.

> Named Static factory method has name

For a constructor, there can be multiple constructors depending on the input parameters. However, the names of these constructors are all the same, and users will be confused when calling them, which one should be called.

After using the static factory method, you can give the method different names according to its function. As long as the name is well chosen, users will know what the method name means when they see it. Knowing this Which method should be called at any time greatly improves the readability of the code.

> Environmental protection You don’t have to create a new object every time you call it

Using the constructor will generate a new object every time.

The static factory method can repeatedly return pre-created objects.

The Boolean above is a very good example. Both TRUE and FALSE variables are pre-created, and they are both immutable final objects. Whoever needs to use them can just return them. , and don’t worry about being modified.

The following is the initialization code for the two variables TRUE and FALSE:


##

public final class Boolean implements java.io.Serializable, 
                   Comparable<Boolean> 
{ 
  /** 
   * The {@code Boolean} object corresponding to the primitive 
   * value {@code true}. 
   */ 
  public static final Boolean TRUE = new Boolean(true); 
 
  /** 
   * The {@code Boolean} object corresponding to the primitive 
   * value {@code false}. 
   */ 
  public static final Boolean FALSE = new Boolean(false); 
 
  ...   
}

> Multiple children can return to the original Objects of any subtype of the return type

Using a constructor, you can only return an object of one type; using a static factory method, you can return the original return type as needed. Objects of any subtype.

Take the noneof method of EnumSet as an example:


/** 
 * Creates an empty enum set with the specified element type. 
 * 
 * @param elementType the class object of the element type for this enum 
 *   set 
 * @throws NullPointerException if <tt>elementType</tt> is null 
 */ 
public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) { 
  Enum[] universe = getUniverse(elementType); 
  if (universe == null) 
    throw new ClassCastException(elementType + " not an enum"); 
 
  if (universe.length <= 64) 
    return new RegularEnumSet<>(elementType, universe); 
  else 
    return new JumboEnumSet<>(elementType, universe); 
}

This method, for performance reasons, specifically returns what type, determined by the number of enumeration types Determine, if it exceeds 64, return JumboEnumSet, otherwise return RegularEnumSet, and these two types are invisible to the user. The user only needs to know that it is an EnumSet.

It is precisely because static factory methods have greater advantages than constructors. When we create a class, our first reaction should not be to provide a public constructor, and we should give priority to static factory methods.

Common static factory method names

Here are some conventional names for static factory methods:


valueOf/ Of——Type conversion, the returned instance has the same value as the input parameter, such as Boolean.valueOf(), EnumSet.valueOf()

getInstance——Return a pre-created instance
newInstance——Return a New instance

Isn’t the static factory method the factory pattern?

Speaking of this, many people may think that this is not the factory model? Answer: Not exactly the same.

The static factory method discussed in this article, like the factory pattern, is a method used to replace the constructor. It has the three advantages mentioned above: named, environmentally friendly, and multiple children.

However, the implementation methods and usage scenarios of the two are different.


First of all, intuitively speaking, in terms of code structure, the factory pattern we are talking about usually requires a xxxFactory class in which the factory method is defined; and the static factory discussed in this article

method, you only need a class, and the class itself provides a factory method for producing objects.


Secondly, let’s think about it. If a class provides a static factory method during design, is it still necessary to use the factory pattern?


Yes, no need.


In other words, we only need to use the factory pattern when a class does not provide a static factory method.


Think about it, if Apple has a powerful parts factory, does it still need Foxconn?

Summary

The static factory method has three major advantages-named, environmentally friendly, and multiple children.


If a class provides a static factory method, then there is no need to consider the factory pattern for this class.


When we create a class, our first reaction should not be to provide a public constructor, but give priority to static factory methods.

The above is the detailed content of Detailed explanation of the use of static factory methods in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools