题目要求:
Following the form of the example Lunch.java, create a class called ConnectionManager that manages a fixed array of Connection objects. The client programmer must not be able to explicitly create Connection objects, but can only get them via a static method in ConnectionManager. When the ConnectionManager runs out of objects, it returns a null reference. Test the classes in main( ).
设计思路:
Connection类的构造方法为私有类型,仅能通过其creatConnection()方法创建Connection对象;在ConnectionManager类中,有一静态Connection对象的引用数组cnns,存储10个Connection对象的引用,topPos 表示当前为null的元素下标,当topPos大于等于10时,说明cnns用于存储Connection对象引用的元素已经耗尽,返回null.
main()方法用于测试,当第11次和12次调用makeConnectionManager()方法时,由于元素耗尽,不会得到一个有效的Connection对象引用。
运行输出:
Connection 1 done
Connection 2 done
Connection 3 done
Connection 4 done
Connection 5 done
Connection 6 done
Connection 7 done
Connection 8 done
Connection 9 done
Connection 10 done
ConnectionManager runs out of objects
ConnectionManager runs out of objects
实现代码:
public class TestMngr { public static void main( String[] args ){ // test the class ConnectionManager's makeConnectionManager method for( int i = 0 ; i < 12 ; i++ ){ Connection ref = ConnectionManager.makeConnectionManager(); if( ref != null ){ System.out.println( "Connection " + ( i + 1 ) + ref.getStatus() ); } // connectionManager can only hold 10 connections , so when i == 10 and i == 11 , it runs out of objects else{ System.out.println( "ConnectionManager runs out of objects"); } } } } class ConnectionManager{ private static Connection[] cnns = new Connection[ 10 ]; // hold 10 connections private static int topPos = 0; public ConnectionManager(){ } public static Connection makeConnectionManager(){ if( topPos < cnns.length){ cnns[ topPos ] = Connection.creatConnection(); return cnns[ topPos++ ]; } else{ // ConnectionManager runs out of objects return null; } } } class Connection{ private String flag = " done"; private Connection() {} public String getStatus(){ return flag; } public static Connection creatConnection () { return new Connection(); } }