2017-09-04 61 views
2

我怎樣才能使我的程序限制以下實例創建四個這樣,當我嘗試創建第五中學是顯示錯誤消息的實例的數量,「學校無法註冊達到最大值「。 感謝一如既往限制創建使用帶有參數的構造函數

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

介紹工廠模式。 – Flown

+1

使用數組和全球個性化......或者在學校靜態counteer –

+0

那麼你已經在你的構造函數中的靜態學校計數器,拋出一個異常,如果正在創建一個又一個? – daniu

回答

2

的示例代碼,你問:

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

老實說,雖然,這不是一個好主意,做這種方式。更好地允許創建無數的學校對象,並有一個單獨的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); 
    } 
} 
+0

兩個好點:講的錯誤是什麼學校的最大數量是(所以程序員收到一些幫助)和移動決定一個SchoolRegistry。後者也可以有一個createSchool方法被稱爲工廠類。 –

+0

關於創建SchoolRegistry的好處! – nagendra547

相關問題