1、对象池技术并没有限制说只能创建一个对象,而且这种技术同样适用于创建固定数量的对象,然而,这种情况下,你就得面对如何共享对象池里的对象这种问题。
当创建多个对象会的代价会很大的时候,可以考虑使用对象池技术,目前已有的技术比如:线程池技术、数据库连接池技术
2、UML图(astah/jude)下载地址:

3、模拟一个数据库连接池进行实现:
实现的接口:
1 package com.xinye.test.pool;
2 /**
3 * 用户需要的实际的东西都实现这个接口
4 * @author xinye
5 *
6 */
7 public interface IConnection {
8 Object get();
9 void set(Object obj);
10 }
实现类:
1 package com.xinye.test.pool;
2 /**
3 * 用户真正需要的东西,比如数据库连接
4 * @author xinye
5 *
6 */
7 public class Connection implements IConnection{
8
9 @Override
10 public Object get() {
11 // TODO Auto-generated method stub
12 return null;
13 }
14
15 @Override
16 public void set(Object obj) {
17 // TODO Auto-generated method stub
18
19 }
20
21 }
实现类的包装对象(添加状态):
1 package com.xinye.test.pool;
2 /**
3 * 池子中放的东西(具有状态以及用户实际需要的东西,实际上就是个包装类)
4 * @author xinye
5 *
6 */
7 public class PoolItem {
8 public boolean isUse;
9 public IConnection conn;
10 public PoolItem(IConnection conn){
11 this.conn = conn;
12 }
13 }
池子管理对象:
1 package com.xinye.test.pool;
2
3 import java.util.ArrayList;
4 /**
5 * 池子管理类
6 * @author wangheng
7 *
8 */
9 public class PoolManager {
10
11 private ArrayList<PoolItem> items = new ArrayList<PoolItem>();
12 /**
13 * 往池子里面放东西
14 * @param conn
15 */
16 public synchronized void add(IConnection conn){
17 items.add(new PoolItem(conn));
18 }
19 /**
20 * 得到池子中的对象
21 * @return
22 * @throws PoolEmptyException
23 */
24 public synchronized IConnection get() throws PoolEmptyException{
25 int len = items.size();
26 for(int i = 0;i < len;i++){
27 PoolItem item = items.get(i);
28 if(item.isUse == false){
29 item.isUse = true;
30 return item.conn;
31 }
32 }
33 throw new PoolEmptyException();
34 }
35 /**
36 * 释放对象
37 * @param conn
38 * @throws PoolEmptyException
39 */
40 public synchronized void release(IConnection conn) throws PoolEmptyException{
41 int len = items.size();
42 for(int i = 0;i < len;i++){
43 PoolItem item = items.get(i);
44 if(conn == item.conn){
45 item.isUse = false;
46 return;
47 }
48 }
49 throw new PoolEmptyException();
50 }
51 /**
52 * 池子是空的异常
53 * @author wangheng
54 *
55 */
56 public static class PoolEmptyException extends Exception{
57 /**
58 *
59 */
60 private static final long serialVersionUID = 5617927009406316965L;
61
62 }
63
64 }
连接池对象:
1 package com.xinye.test.pool;
2
3 import com.xinye.test.pool.PoolManager.PoolEmptyException;
4
5 /**
6 * 用户真正需要关心的池子
7 * @author xinye
8 *
9 */
10 public class ConnectionPool {
11 private static PoolManager manager = new PoolManager();
12 /**
13 * 批量添加连接对象
14 * @param count
15 */
16 public static void addConnections(int count){
17 for(int i = 0;i < count;i++){
18 manager.add(new Connection());
19 }
20 }
21 /**
22 * 得到连接对象
23 * @return
24 * @throws PoolEmptyException
25 */
26 public static IConnection getConnection() throws PoolEmptyException{
27 return manager.get();
28 }
29 /**
30 * 释放链接
31 * @param conn
32 * @throws PoolEmptyException
33 */
34 public static void release(IConnection conn) throws PoolEmptyException{
35 manager.release(conn);
36 }
37 }