限制构造函数

时间:2016-02-07 10:19:27

标签: java

public class Office {
private char building;
private int floor;
private int roomnumber;}

public class Employee {
private String firstname;
private String lastname;
private String mail;
private String phone;
private Office office;}

我正在使用Java创建一个Office,并且每个员工只能限制一个办公室,这意味着Office的每个实例只能由一个Employee使用。 Office由Office Class制作,包含在Employee Class中。有没有人对如何做到这一点有任何建议?

2 个答案:

答案 0 :(得分:1)

如果您的意思是只想创建一个Office对象,则需要执行以下操作: 您可以拥有boolean类型的静态类变量,一旦第一个实例生成,您将更改为true。在创建一个新实例时,您将检查此布尔值是否为真,如果是,则可以抛出异常等。
示例:

private static boolean hasBeenInstanciated = false;

public Constructor(){
    if(hasBeenInstanciated){
        throw new IllegalStateException("This class has already been instanciated once!");
    }else hasBeenInstanciated = true;
//The rest of your constructor code goes here.
}

答案 1 :(得分:1)

这是一种方法:

  1. 创建Set<String>并开始将building_floor_roomnumber作为密钥放置。
  2. 在初始化Office之前,检查“设置”中是否已存在building_floor_roomnumber
  3. 这是一个展示它的小片段:

    public static void main (String[] args) 
    {
        /* You can also make it global; depending on your needs */
        Set<String> office = new HashSet<>();
        String key = "A12-London_F6_R121";
    
        if(office.contains(key)) {
            System.out.println("Already Taken!");
        } else {
            office.add(key);
    
            /* Create New Office Object & Initialize it */
            Office off = new Office();
            off.setBuilding("A12-London");
            off.setFloor("F6");
            off.setRoom("R121");
    
            /* Set it back to Employee Object */
            /* I'm assuming you have some Employee Object named emp */
            emp.setOffice(off);
    
            System.out.println("Added Successfully!");
        }
    }