The main purpose of the enjoy meta-mode is to share the shared pool, which can reduce the overhead of memory when there are many objects in the system, and is usually used in conjunction with the Factory mode.
Flyweightfactory is responsible for creating and managing the unit of entitlement, and when a client requests, the factory checks to see if there are any eligible objects in the current object pool, and if so, returns an already existing object, and if not, creates a new object, flyweight is a superclass. A reference to the shared pool, we can easily associate with the Java JDBC Connection pool, think of the characteristics of each connection, we can not be difficult to summarize: for the sharing of some objects, they have a number of common properties, take the database connection pool, URL, Driverclassname, Username, password and dbname, these properties are the same for each connection, so it is appropriate to use the enjoy meta-mode to process, build a factory class, the above-mentioned similar attributes as internal data, and other as external data, in the method call, as a parameter passed in, This saves space and reduces the number of instances.
Look at an example:
Look at the code for the database connection pool:
[Java]View Plaincopy
- Public class ConnectionPool {
- Private Vector<connection> Pool;
- /* Public Properties */
- 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 initialization work */
- Private ConnectionPool () {
- Pool = new vector<connection> (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 ();
- }
- }
- }
- /* Return connect to Connection pool */
- Public synchronized void release () {
- POOL.ADD (conn);
- }
- /* Returns a database connection in the connection pool */
- Public synchronized Connection getconnection () {
- if (Pool.size () > 0) {
- Connection conn = pool.get (0);
- Pool.remove (conn);
- return Conn;
- } Else {
- return null;
- }
- }
- }
Through the management of connection pool, it realizes the sharing of database connection, does not need to recreate the connection every time, saves the cost of database re-creation, and improves the performance of the system!
Enjoy meta mode (Flyweight)