The use of static factory method

scenes to be used:

1. Static method, although the same is to instantiate an object, but does not necessarily coincide with the class name in the syntax is more flexible and easier to express in the name of the instance of purpose

2. The method of construction may be private, by only instantiating static factory method to do, i.e., not exposed to the client constructor, and in a static method can do more (such as single embodiment, different instances of the parameter values )

3. instance of a subclass can be returned as a result, in the case of using subclasses client unconscious while the subclass protected client can not instantiate subclasses, and the subsequent upgrades may be implemented within the method, the client It will not be perceived.

4. The service provider framework

example:

1.java Collections of tools is that by the method of Example 3 above that can not be instantiated directly set type, and named as a flexible, easy to use

2.jdbc mode is 4. In the above-described method DriverManager.getConnection, returns the instance is not specified by the first specific type of database vendor to implement Connection then registered to the system:

Load the driver:

1 Class.forName(driverClass);
2 //加载MySql驱动
3 Class.forName("com.mysql.jdbc.Driver");
4 //加载Oracle驱动
5 Class.forName("oracle.jdbc.driver.OracleDriver");

Get database connection:

 1 DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/fireway", "root", "root"); 

Create a Statement / PreparedStatement objects:

1 conn.createStatement();
2 conn.prepareStatement(sql);

 

Guess you like

Origin www.cnblogs.com/lccsblog/p/10988467.html
Recommended