【问题标题】:Limit the number of Instances Created Using A constructor with Parameters限制使用带参数的构造函数创建的实例数
【发布时间】:2017-09-04 12:51:56
【问题描述】:

如何使我的程序将以下实例创建限制为四个,以便在我尝试创建第五所学校时显示错误消息“学校无法注册达到最大值”。 一如既往的感谢

public class Driver {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Header h1 = new Header();
        h1.schoolHeader();
        School s1 = new School("Pascoe Vale High School", "101");
        School s2 = new School("North Melbourne Primary School", "102");
        School s3 = new School("St Aloysuis College", "103");
        School s4 = new School("Coburg High School", "104");
        School s5 = new School("Chuka Nwobi High School", "105");
    }
}

class School {
    public static int objCount = 0;
    private static String regId;
    private String name;

    School(String name, String regId) {
        this.name = name;
        this.regId = regId;
        System.out.println("*** Successfully registered " + getName());
        objCount++;
    }

    public void registerHeader() {
        System.out.println("--- Registering Participating Schools---");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRegId() {
        return regId;
    }
    public void setRegId(String regId) {
        this.regId = regId;
    }
}

【问题讨论】:

  • 引入工厂模式。
  • 使用数组和全局计数...或者在学校中使用静态计数器
  • 那么您的构造函数中已经有了静态 School 计数器,如果正在创建另一个,则抛出异常?
  • 老实说,我可能是在 3 周前才开始编程,所以我是一个完整的初学者
  • @daniu 你能写一个示例代码吗?谢谢

标签: java object instance


【解决方案1】:

您要求的示例代码:

static final int ALLOWED_COUNT = 4;

public School(String name, String regId) {
    if (objCount >= ALLOWED_COUNT) {
        throw new TooManySchoolsException("Only " + ALLOWED_COUNT + " schools allowed!");
    }
    this.name = name;
    this.regId = regId;
    System.out.println("*** Successfully registered " + getName());
    objCount++;
}

老实说,这样做并不是一个好主意。允许创建无限数量的 School 对象并拥有一个单独的 SchoolRegistry 类来跟踪注册的学校数量要好得多。

class SchoolRegistry {
    static final int MAX_SCHOOLS = 4;
    private List<School> schools = new ArrayList<>();
    public void register(School s) {
        if (schools.size() > MAX_SCHOOLS) throw new TooManySchoolsException();
        schools.add(s);
    }
}

【讨论】:

  • 两个优点:告诉错误学校的最大数量是多少(因此程序员会得到一些帮助),并将决定转移到 SchoolRegistry。后者也可以有一个 createSchool 方法被称为工厂类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
相关资源
最近更新 更多