Home » Java » The design mode of Flyweight

The design mode of Flyweight

imagine, in the low level of granularity when (fine-grained) object is very good, but the cost was prohibitive. The flyweight pattern is a non shared part off until some method is invoked to provide a method of.


public, class, ConnectionPool {
Private Vector pool;
/ * * / public property
Private String url = "jdbc:mysql://localhost:3306/test"";
Private String username = "root"";
Private String password = "root"";
Private String driverClassName = "com.mysql.jdbc.Driver"";
Private int poolSize = 100;
Private, static, ConnectionPool, instance = null;
Connection conn = null;
/ * construction method, do some initial work.
Private, ConnectionPool () {
Pool = new, Vector (poolSize);
For (int i = 0; I < poolSize; i++) {
{try
Class.forName (driverClassName);
Conn = DriverManager.getConnection (URL, username, password);
Pool.add (conn);
} catch (ClassNotFoundException, e) {
E.printStackTrace ();
} catch (SQLException, e) {
E.printStackTrace ();
}
}
}
/ * returns the connection to the connection pool.
Public, synchronized, void, release () {
Pool.add (conn);
}
/ * returns the connection to a database connection in the pool.
Public, synchronized, Connection, getConnection () {
If (pool.size () > 0) {
Connection conn = pool.get (0);
Pool.remove (conn);
Return conn;
} else {
Return null;
}
}
}




Latest