01. Static factory method substitution constructor, 01 Constructor
Consider replacing the constructor with a static factory Method
The reason for using the static factory method to replace the constructor is as follows:
Consider the following program:
Random random = new Random();
BigInteger integer = BigInteger.probablePrime(3, random);
The meaning of this Code is to return a BigInteger object that is likely to be a prime number and has a length of 3. Here the length is only the length after the integer is converted to the binary value; it is likely that the probability of not a prime number cannot exceed 2-100.
However, if the constructor: BigInteger (int, Random) is used, it is difficult to guess what is returned through parameters.
2. You do not need to create a new object every time you call the static factory method.
If some immutable classes have already created instances before they are used, or cached the created instances, they can be directly used in actual use, this avoids unnecessary duplicate objects. The following is an example that has been used in actual use:
Boolean b = Boolean.valueOf(true);
The meaning of this line of code is to create a Boolean object with a value of true. Let's take a look at its source code:
public static Boolean valueOf(boolean b) { return (b ? TRUE : FALSE); }
TRUE and FALSE are defined as follows:
public static final Boolean TRUE = new Boolean(true);public static final Boolean FALSE = new Boolean(false);
Obviously, these two classes are directly defined as immutable classes and can be reused. If the same object needs to be created frequently in some services and the object creation cost is relatively high, this method can significantly improve the performance.
3. Use the static factory method to return any child type objects of the original return type.
If an API can return an object, but it does not convert the class of the object to public, this method hides the implementation class and makes the API concise.
For specific instances, almost all implementations of Java Collections Framework's collection interfaces are exported in a class that cannot be instantiated through a static factory method.
Network piracy:
Service Provider Framework)
The author mentioned that the class of the object returned by the static factory method does not need to exist when writing the class of the static factory method. Multiple service providers implement one service. The system provides multiple implementations for the client of the service provider and decouples them from multiple implementations.
Service Provider framework components: Service Interface, Provider Registration API, and Service Access API) and optional component Service Provider Interface ).
It seems a little hard to understand... Biubiu ~
For JDBC: Connection is a service interface; DriverManager. RegisterDriver is the provider registration API; DriverManager. getConnection is the service access API; Driver is the service provider interface.
(PS: Do you forget about JDBC? Can it be written by hand? Take out a small notebook and write it down ...)
Public static void main (String [] args) throws ClassNotFoundException, SQLException {
String URL = "jdbc: mysql: // 127.0.0.1: 3306/study? UseUnicode = true & amp; characterEncoding = UTF-8 ";
String USER = "root"; // USER Name
String PASSWORD = "xxxxx"; // your MySQL PASSWORD
// 1. Load the driver
Class. forName ("com. mysql. jdbc. Driver ");
// 2. Obtain the database link
Connection conn = DriverManager. getConnection (URL, USER, PASSWORD );
// 3. Operate the database through the database connection to add, delete, modify, and query (using the Statement class)
Statement st = conn. createStatement ();
ResultSet rs = st.exe cuteQuery ("select * from user ");
// 4. process the returned results of the database (using the ResultSet class)
While (rs. next ()){
System. out. println (rs. getString ("username") + "" + rs. getInt ("age "));
}
// Close the resource
Rs. close ();
St. close ();
Conn. close ();
}
It is a bit nonstandard, but its functions can be implemented. If Maven is used to manage projects, you need to add:
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency>
The following is a specific template for your reference. You can use it with a slight modification later ~ :
// This is the Service Interface
Public interface Service {
// Methods
}
// This is the Service Provider Interface.
Public interface Provider {
Service newService ();
}
// This is a class that cannot be directly instantiated for registration and access.
Public class Services {
Private Services () {// disable instantiation
}
Private static final Map <String, Provider> providers = new ConcurrentHashMap <String, Provider> ();
Public static final String DEAFULT_PROVIDER_NAME = "default ";
// Provides the Registration API Provider Registration API
Public static void registerdefadefaprovider (Provider provider ){
RegisterProvider (DEAFULT_PROVIDER_NAME, provider );
}
Public static void registerProvider (String name, Provider provider ){
Providers. put (name, provider );
}
// Service Access API
Public static Service newInstance (){
Return newInstance (DEAFULT_PROVIDER_NAME );
}
Public static Service newInstance (String name ){
Provider provider = providers. get (name );
If (null = provider ){
Throw new IllegalArgumentException ("No Provider registered with name" + name );
}
Return provider. newService ();
}
}
Disadvantages
Any method has more or less advantages and disadvantages. There is no best method. There is only the most suitable method. You should fully understand the advantages and disadvantages of a new method, and then, based on your actual situation, select the most appropriate method.
1. If the class does not include a public or protected constructor, it will not be able to be divided into categories ~
2. In fact, there is no difference between the static factory method and other static methods. After all, the implementation method is similar ~
Common static factory methods are also straightforward:
- ValueOf: Generally, the returned instance has the same value as the parameter.
- Of: it is simpler than valueOf and has similar meanings.
- GetInstance: returns a specific instance. You can specify parameters for specific differences. If Singleton is used, a unique instance is returned if no parameter exists.
- GetType: literal meaning, return object type, so easy.
Reference: Valid Java Chinese version (second edition)