java:保证类型只有一个实例

java: ensure that there is only one instance of the type

我正在遵循以下示例:
https://www.baeldung.com/java-composite-pattern

public class FinancialDepartment implements Department {

    private Integer id;
    private String name;

    public void printDepartmentName() {
        System.out.println(getClass().getSimpleName());
    }

    // standard constructor, getters, setters
}
public class SalesDepartment implements Department {

    private Integer id;
    private String name;

    public void printDepartmentName() {
        System.out.println(getClass().getSimpleName());
    }

    // standard constructor, getters, setters
}

public class HeadDepartment implements Department {
    private Integer id;
    private String name;

    private List<Department> childDepartments;

    public HeadDepartment(Integer id, String name) {
        this.id = id;
        this.name = name;
        this.childDepartments = new ArrayList<>();
    }

    public void printDepartmentName() {
        childDepartments.forEach(Department::printDepartmentName);
    }

    public void addDepartment(Department department) {
        childDepartments.add(department);
    }

    public void removeDepartment(Department department) {
        childDepartments.remove(department);
    }
}

我想阻止我自己将两个相同类型添加到 HeadDepartment

例如,如果它为同一类型调用 add addDepartment 两次,则应该只有一个

public class CompositeDemo {
    public static void main(String args[]) {
        Department salesDepartment = new SalesDepartment(
          1, "Sales department");

        Department salesDepartment2 = new SalesDepartment(
          1, "Sales department");
        Department salesDepartment3 = new SalesDepartment(
          3, "Sales department");


        Department financialDepartment = new FinancialDepartment(
          2, "Financial department");

        HeadDepartment headDepartment = new HeadDepartment(
          3, "Head department");

        headDepartment.addDepartment(salesDepartment);
        headDepartment.addDepartment(financialDepartment);

        // only keep the latest of same instanceof ie replace
        headDepartment.addDepartment(salesDepartment2);
        headDepartment.addDepartment(salesDepartment3);

        // this should only print twice one for salesDepartment3 and financialDepartment
        headDepartment.printDepartmentName();

    }
}

我想我只是迭代列表,如果是instanceof,替换并放置?

public void addDepartment(Department department) {
        childDepartments.add(department);
    }

如果 instnaceof Department 是第一个,我也想保留订单,我希望它保持第一个,这意味着它应该在 financialDepartment 之前打印 salesDepartment3

您的 addDepartment() 需要遍历子项列表并将每个子项的 class 与您要添加的对象的 class 进行比较。 伪代码:

Class addClass = itemToAdd.getClass();
for each child
{
    if (child.getClass() == addClass)
    {
        //class is already in the list so replace it.
    }