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

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

©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页