Detailed 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
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
getInstance——Return a pre-created instance
newInstance——Return a New instance
Isn’t the static factory method the factory pattern?
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.
Summary
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!

Start Spring using IntelliJIDEAUltimate version...

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...

Java...

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...

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...

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

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 SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools