Application of design patterns in Java Database Programming (2)

Source: Internet
Author: User

Http://www.35java.com/zhibo/forum.php? MoD = viewthread & tid = 261 & extra = Page % 3d2

4. Use Singleton mode to control the uniqueness of connection pool objects. We already have the connection pool class connectionpool for managing database connections. Note that the connection pool objects should be unique during system operation. The reason is very simple. If it is not unique, different connection pool objects will be generated for access to different databases, then the connection pool objects will not function at all. Of course, you can also Program Only one connection pool object is created, but this cannot ensure that other programmers can do this. In this case, the singleton mode should be used to obtain the unique connection pool object through the getinstance () method.
Public
Class Connectionpool ......
Public
Class Connectionpool {
Private
Static Connectionpool instance =
Null ;
Public
Static Synchronized connectionpool getinstance (){
If (Instance = Null )
Instance = New Connectionpool ();
Return Instance;
}
Private Connectionpool (){
......
}
}

At this point, the task of creating a database connection has been completed.
5. Extract the operating framework using the template method mode
Database operations can be divided into two types: For the first type of operations, certain result sets will be generated, such as querying the database; for the other type of operations, only changes to the original database are allowed, no result set is generated, such as insert or update operations. For these two cases, we can encapsulate them into corresponding classes. However, we found that these two classes have many similarities during operations. The basic process is to first obtain the database connection, then generate the statement object, and then call the method to execute the SQL statement on this statement object. These steps can be extracted into a method execute () to a parent class, which can be called the dbbean class. This parent class only publishes a method for the subclass to be reloaded. This method is often called the Hook method, which may be called executesql () here (). With this parent class, two sub-classes are generated for two different operation types, namely selectbean and updatebean. For different sub-classes, only the executesql () method of the hooks in the parent class is reloaded to execute different database accesses, so you do not have to worry about preparing for this access.
6. Introduce the adapter mode to solve the inconsistency of existing interfaces.
In the interfaces provided by JDBC, the database access methods are executequery () and executeupdate (). After the template method mode is introduced, the submethod executesql () published in the parent class must be reloaded in the subclass. The name of this submethod is unique, to enable our specific database access to be well connected, we can introduce the adapter mode to adapt these two methods to executesql (). Note that because the executequery () method has a return value, it is necessary to add a member variable rs of the resultset class to the subclass containing it. In this way, in the executesql () method, you only need to assign the return value of executequery () to Rs.
7. Introduce the facade mode to bring the operation interface closer to the business logic
When you use the interface executequery () provided by JDBC to query a database, the returned result is a resultset object, which stores each column to be queried in sequence. To obtain the required information, a programmer must call the GetObject (int I) method of the returned object. In doing so, on the one hand, it is not intuitive, on the other hand, Code High coupling. In this regard, we think of introducing the adaptor mode, which can further remove our interfaces from database operations, so that we can focus more on business logic.
Assume that there is a student info table t_student with the Information ID, name, and age. The basic table structure is as follows:
For this Table query, we aim to obtain data using methods such as GETID (), getname (), and getage. For this purpose, what we need to do now is to correctly locate the returned values of our methods based on the data obtained by the query. For database queries, we found that the sequence numbers of the records to be queried in the query statement correspond one to one with the sequence numbers in the returned results, you can put the field name to be queried in a vector. For example, the content in the vector above can be ("ID", "name", "Age "), the SQL statements we want to execute are easily spliced by these field names. The execution results are placed in the resultset object in the given order. Finally, for specific function calls, such as GETID (), you can obtain the function name through the reflection mechanism provided by Java, and then remove the previous get characters, in the field name vector, use the indexof (Object O) method to obtain the index of the serial number corresponding to the field name, which is also the serial number in the resultset of the query result, you can get the expected result through GetObject (INDEX) in the query result resultset. We can extract the unchanged code to the parent class selectbean. The advantage of this is that different table structures can be used to generate corresponding child classes. We only need to define a vector variable, put the field name string we want to query, and define the corresponding get function. When we call them, we only need to call the Public matching code of the above parent class to obtain the correct data. The following is the code snippet after the facade mode is introduced to the above table structure:
......
String name, ID, age;
Studentselect student =
New Studentselect ();
Student.exe cute ();
Name = Student. getname ();
ID = Student. GETID ();
Age = Student. getage ()
......

The above mechanism can also be used for SQL statements updated in the database. This method is similar and will not be described here.
This article provides an idea to introduce design patterns in Java database programming. In practice, we have implemented a framework based on the above design ideas. Based on this framework, the efficiency of writing Java data software is greatly improved. Of course, this article provides an overall design concept. In practice, you can modify some modules based on specific situations. For example, database connections can be obtained from data sources in J2EE. Readers can choose this option on their own.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.