What do you mean by using a static factory method instead of a constructor?

Asked 2 years ago, Updated 2 years ago, 60 views

I was working on the Java program, and my friend told me to use the static factory method instead of the creator. I didn't tell you why, but I don't know what this means.

static constructor java factory

2022-09-22 12:53

1 Answers

You use the public constructor to create a normal class of objects. In addition to this method, there is also a way to make a public static factory method. This method creates an instance of the class and returns it Using the static factory method instead of constructors has the following advantages and disadvantages:

1. You can have your own name. Unlike the constructor, it has its own name, which makes it easier for other users to understand what this method does.

You can prevent the creation of new objects each time they are called.
To prevent unnecessary duplication of instances, you can save and repeat instances that have already been created, and make them available again.

There is no restriction on the type of object that can be returned. The static factory method allows you to select the data type to return, providing excellent flexibility when you need to select a class of objects.

It simplifies the code for generating an instance of a parameterization type. Using the static factory method, the compiler solves the type parameters. This is called type inference and it is easy to understand by looking at the source below. Map<String, List<String>> m = new HashMap<String, List<String>>(); Typing is difficult and complicated. At this time, it is assumed that the following static factory method is provided in HashMap Assumptions do not actually exist.

public static <K,V> HashMap<K,V> newInstance(){
return new HashMap<K,V>();
}
Map<String, List<String>> m = new HashMap.newInstance();

Although the type parameter was given twice in a row, it can be seen that it was reduced to one time by providing the static method.

So, what are the disadvantages?


2022-09-22 12:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.