Home > Java > javaTutorial > body text

Detailed explanation of the use of static factory methods in Java

黄舟
Release: 2017-09-09 13:11:35
Original
1682 people have browsed it

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); 
}
Copy after login

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); 
 
  ...   
}
Copy after login

> 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); 
}
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template