CSDN博客

img chunfa1980

Java设计模式

发表于2004/4/6 15:21:00  531人阅读

1:单实例类

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();
 
 }


}

适合于数据库连接池的使用,但是单实例很难扩展,,应该呗设计为并行执行。因为多线程将访问同一个单实例对象。

0 0

相关博文

我的热门文章

img
取 消
img