【Java】【TIJ】让类的对象个数受控于我们——实现类对象个数的限制

来源:互联网 发布:php htmlspecialchars 编辑:程序博客网 时间:2024/05/29 19:07

下面介绍一个限制类对象个数的例子:

创建一个名为ConnectionManager的类,该类管理一个元素为Connection对象的固定数组。客户端程序员不能直接创建Connection对象,而只能通过ConnectionManager中的某个static的方法来获取它们。当ConnectionManager之中不再有对象时,它会返回null引用。在main()之中检测这些类。

/*** Thinking in Java test 6.8(限制类对象个数)* @author:WolfOfSiberian* @email:QuietWolf@yeah.net*/import java.sql.DriverManager;import java.sql.Connection;import java.sql.SQLException;public class ConnectionManager{        //最大连接数private static final int connMax = 10;//Connection对象静态数组private static Connection connArray[] = new Connection[connMax];//当前使用的连接数private static int countUse = 0;private ConnectionManager(){//}/***  获取Connection对象*/public static Connection getConnection()throws Exception{if(countUse >= connMax){System.out.println("Sorry,There is no Connection Object for you to use!");return null;}else{                        Class.forName("com.mysql.jdbc.Driver").newInstance();//加载连接MySQL数据库的驱动程序        connArray[countUse] = DriverManager.getConnection("jdbc:mysql://localhost/test?"+"user=root&password=sine88");//获取连接对象Connection       countUse++;//使用连接数加一,可用的连接数却少了一个System.out.println("这是第"+countUse+"个Connection");    return connArray[countUse-1];}}/*** 释放Connection对象*/public static void freeConnection()throws Exception{for(int i=0;i<countUse;i++){connArray[i].close();connArray[i] = null;}}//main入口public static void main(String[] args)throws Exception{for(int i=0;i<11;i++){Connection conn = ConnectionManager.getConnection();}ConnectionManager.freeConnection();}}


运行结果

针对本类实现的Connection对象的回收存在的缺陷,作者重新实现了一个完善版本http://blog.csdn.net/wolfofsiberian/article/details/39889093)

F:\01 Java\01 Project\01 TinkingInJava>java ConnectionManager
这是第1个Connection
这是第2个Connection
这是第3个Connection
这是第4个Connection
这是第5个Connection
这是第6个Connection
这是第7个Connection
这是第8个Connection
这是第9个Connection
这是第10个Connection
Sorry,There is no Connection Object for you to use!

0 0
原创粉丝点击