Java 习题 (57) **

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

解答:
先放Lunch.java代码:

class Soup1 {
	private Soup1() {}

	public static Soup1 makeSoup() {
		return new Soup1();
	}
}

class Soup2 {
	private Soup2() {}

	private static Soup2 ps1 = new Soup2();

	public static Soup2 access() {
		return ps1;
	}

	public void f() {}
}

public class Lunch {
	void testPrivate() {
		// Can't do this! Private constructor
		//! Soup1 soup = new Soup1();
	}

	void testStatic() {
		Soup1 soup = Soup1.makeSoup();
	}

	void testSingleton() {
		Soup2.access().f();
	}
}

现在就根据上面的Lunch.java代码,来完成这道题目。

package six.eight;

public class eightExercise {
    public static void main(String[] args) {
        Connection c = ConnectionManager.getConnection();
        while(c != null) {
            System.out.println(c);
            c.doSomething();
            c = ConnectionManager.getConnection();
        }
    }
}
package six.eight;

public class Connection {
    private static int counter = 0;
    private int id = counter++;
    Connection() {}
    public String toString() {
        return "Connection " + id;
    }
    public void doSomething() {}
}
package six.eight;

public class ConnectionManager {
    private static Connection[] pool = new Connection[10];
    private static int counter = 0;
    static {
        for(int i = 0; i < pool.length; i++) {
            pool[i] = new Connection();
        }
    }

    public static Connection getConnection() {
        if(counter < pool.length)
            return pool[counter++];
        return null;
    }
}

结果如下:
在这里插入图片描述
如果觉得不错,就用点赞或者关注或者留言,来代替五星好评吧~
谢谢各位~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值