Java design pattern

zhaozj2021-02-16  49

1: Single Class

public class ConnectionPool {// only one instance is needed private static ConnectionPool instance; private ConnectionPool () {System.out.println ( "Createing the single instance of connection pool");}

public static ConnectionPool getInstance () {if (! instance = null) {System.out.println ( "Getting existing instance of connection pool"); return instance;} else {instance = new ConnectionPool (); return instance;}

} Public static void main (String args []) {System.out.println ( "Get connection pool first time"); ConnectionPool cPool = ConnectionPool.getInstance (); System.out.println ( "Get Connection pool second time") ConnectionPool AnnotherPool = connectionPool.getInstance ();

}

Suitable for the use of database connection pools, but single instance is difficult to extension, should be designed to perform parallelism. Because multi-thread will access the same single instance object.

转载请注明原文地址:https://www.9cbs.com/read-23100.html

New Post(0)