Singleton mode in Java

Source: Internet
Author: User

1 Singleton mode ensures that a class has only one instance and provides the instance to the entire system.
2 features:
3 1. One class can only have one instance
4 2. Create your own instance
5 3. Use this instance throughout the system
6 Examples: In the following object diagram, there is a "singleton object ", "Customer A", "Customer B", and "customer C" are the three customer objects of the singleton object. As you can see, all customer objects share one singleton object. In addition, we can see from the singleton object to its own connection line that the singleton object holds a reference to itself.
7
8. The Singleton mode is mainly used to ensure that only one instance of a class exists in a Java application. In many operations, such as creating a directory database connection, such single-threaded operations are required. Some resource managers are often designed to work in singleton mode.
9 external resources: for example, each computer can have several printers, but only one printer spooler can be used to prevent two print jobs from being output to the printer at the same time. Each computer can have several communication ports. The system should centrally manage these communication ports to prevent a communication port from being called by both requests at the same time. For example, most software has one or more attribute files to store system configurations. Such a system should be managed by an object.
10
11. Example: Windows recycle bin.
12 In the entire Windows system, the recycle bin can only have one instance, and the entire system uses this unique instance, and the recycle bin provides its own instance. Therefore, the recycle bin is a singleton application.
13
14 two forms:
15 1, hunger type Singleton
16 public class Singleton {
17
18 private Singleton (){}
19
20 // define your own instance internally. Isn't it strange?
21 // note that this is private for internal calls only
22
23 Private Static Singleton instance = new Singleton ();
24
25 // here we provide a static method for external access to this class, which can be accessed directly.
26 public static Singleton getinstance (){
27 return instance;
28}
29}
30
31 2, lazy Singleton type
32
33 public class Singleton {
34
35 Private Static Singleton instance = NULL;
36
37 public static synchronized Singleton getinstance (){
38
39 // This method is better than above. You don't need to generate objects every time, just for the first time.
40
41
42 // The instance is generated during use, improving the efficiency!
43 If (instance = NULL)
44 instance = new Singleton ();
45 return instance ;}
46
47}
48
49
The second part of 50 is in the form of lazy initialization. That is to say, the initial Singleton during the first call will not be regenerated in the future.
51
52
53 Note that synchronized in the form of lazy Initialization is very important. If synchronized is not available, you may obtain multiple Singleton instances by using getinstance.
54. Generally, the first type is safer.
55
56. Connect to the MySQL database using Java in singleton Mode
57
58 package com. Adrop. util;
59
60
61
62 import java. SQL .*;
63
64
65
66 public class dbmanager {
67
68 // User Name
69
70 Private string user = "";
71
72 // Password
73
74 private string Password = "";
75
76 // host
77
78 private string host = "";
79
80 // Database Name
81
82 private string database = "";
83
84 // Private dbmanager dBm = NULL;
85
86
87
88 /*
89
90 private string url = "JDBC: mysql: //" + host + "/" + "useunicode = true & characterencoding = gb2312 ";
91
92 */
93
94 private string url = "";
95
96 private connection con = NULL;
97
98
99
100 statement stmt;
101
102 /**
103
104 * private constructor ensures that external entities cannot be instantiated. dbmanager can only provide self-built Constructor
105
106 * existing instances, and only one instance can be created.
107
108 * the connection is established based on the host, database name, database user name, and database user password.
109
110 * @ Param host string
111
112 * @ Param database string
113
114 * @ Param user string
115
116 * @ Param password string
117
118 */
119
120 private dbmanager (string host, string database, string user, string password ){
121
122
123
124 this. Host = host;
125
126 This. Database = database;
127
128 this. User = user;
129
130 this. Password = password;
131
132 // display Chinese Characters
133
134 this. url = "JDBC: mysql: //" + host + "/" + database +
135
136 "? Useunicode = true & characterencoding = gb2312 ";
137
138
139
140 try {
141
142 class. forname ("org. gjt. Mm. MySQL. Driver ");
143
144}
145
146 catch (classnotfoundexception e ){
147
148 system. Err. println ("class not found:" + E. getmessage ());
149
150}
151
152
153
154 try {
155
156 con = drivermanager. getconnection (this. url, this. User, this. Password );
157
158 // The connection type is resultset. type_scroll_insensitive and resultset. concur_read_only.
159
160 stmt = con. createstatement (resultset. type_scroll_insensitive,
161
162 resultset. concur_read_only );
163
164}
165
166 catch (sqlexception ){
167
168 system. Err. println ("SQL exception:" + A. getmessage ());
169
170}
171
172}
173
174 /**
175
176 * Static factory method to obtain a dbmanager instance
177
178 */
179
180 public static dbmanager getinstance (string host, string database, string user, string password ){
181
182 If (DBM = NULL ){
183
184 dBm = new dbmanager (host, database, user, password );
185
186}
187
188 return dBm;
189
190}
191
192 /**
193
194 * returned connection
195
196 */
197
198 public connection getcon (){
199
200 return con;
201
202}
203
204 /**
205
206 * execute a simple query statement
207
208 * returned result set
209
210 */
211
212 public resultset executequery (string SQL ){
213
214 resultset rs = NULL;
215
216 try {
217
218 rs = stmt.exe cutequery (SQL );
219
220}
221
222 catch (sqlexception e ){
223
224 E. printstacktrace ();
225
226}
227
228 Return Rs;
229
230}
231
232 /**
233
234 * execute a simple update statement
235
236 * If the execution is successful, true is returned.
237
238 */
239
240 public Boolean executeupdate (string SQL ){
241
242 Boolean v = false;
243
244 try {
245
246 v = stmt.exe cuteupdate (SQL)> 0? True: false;
247
248}
249
250 catch (sqlexception e ){
251
252 E. printstacktrace ();
253
254}
255
256 finally {
257
258 return V;
259
260}
261
262}
263
266}

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.