How to realize the lazy style of java design pattern
This article mainly introduces the relevant knowledge of "how to realize the lazy style of java design pattern". The editor shows you the operation process through the actual case, the operation method is simple and fast, and the practicality is strong. I hope this article "how to realize the lazy style of java design pattern" can help you solve the problem.
/ / lazy private static readonly object obj = new object (); private static DbConnection dbConnection Private DbConnection () {} public static DbConnection getDbConnection () {if (dbConnection = = null) {lock (obj) {if (dbConnection = = null) {dbConnection = new DbConnection () } return dbConnection;} public void openConnection () {Console.WriteLine ("Open database connection");} / / hungry Chinese private static readonly DbConnection dbConnection = new DbConnection () Private DbConnection () {} public static DbConnection getDbConnection () {return dbConnection;} public void openConnection () {Console.WriteLine ("Open database connection");} / / lazy / / DbConnection dbConnection= DbConnection.getDbConnection (); / / DbConnection dbConnection2 = DbConnection.getDbConnection () / / dbConnection.openConnection (); / / if (dbConnection = = dbConnection2) / / {/ / Console.WriteLine ("the same"); / /} / / Console.ReadLine (); / / hungry DbConnection dbConnection = DbConnection.getDbConnection (); DbConnection dbConnection2 = DbConnection.getDbConnection () If (dbConnection = = dbConnection2) {Console.WriteLine ("same");} Console.ReadLine ()
Summary: make sure that there is only one instance of the class (do your own instantiation) and provide a global access point.
Lazy: instantiated when first referenced, does not take up resources in advance, but requires double locks to ensure thread safety.
Hungry Chinese style: it is instantiated when it is loaded, and resources need to be occupied in advance.
Different from static methods:
1. Objects in static methods will be released after use, and frequent use of release also consumes resources; a singleton will always exist because there is an instantiation.
2. The singleton can inherit the class, implement the interface, and the method can be overloaded.
3. Single case is more flexible than static method.
This is the end of the content about "how to realize the lazy style of java design pattern". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.