设计的一个类只允许创建一个实例,如何写出类的框架代码。
设计的类最多只能创建3个实例,如何修改代码?
设计一个类,在程序运行时才决定它最多能创建的实例个数,这又如何设计它?

解决方案 »

  1.   


    package test;import java.util.Random;/**
     * 一个的
     */
    class Test {
    private static Test test = new Test(); private Test() { } public static Test getTest() {
    return test;
    }
    }/**
     * 三个的
     */
    class Test2 {
    private static Test2[] tests = new Test2[3]; private Test2() { } public static Test2 getTest2() {
    return tests[new Random().nextInt() % 3];
    } public static Test2[] getTest2s() {
    return tests;
    }
    }/**
     * N个的
     */
    class Test3 {
    private static Test3[] tests = null;
    private static int classNum;
    private static boolean isInit = false; private Test3() { } public static void init(int objectNum) {
    if (!isInit) {
    tests = new Test3[objectNum];
    classNum = objectNum;
    }
    } public static Test3 getTest3() {
    if (tests == null) {
    throw new RuntimeException("请先调用init方法初始化");
    }
    return tests[new Random().nextInt() % classNum];
    } public static Test3[] getTest3s() {
    if (tests == null) {
    throw new RuntimeException("请先调用init方法初始化");
    }
    return tests;
    }
    }乱盖的.. 不过调用的时候才说明生成几个对象 应该用工厂什么的去完成..没时间了 随便误导下人吧