java:确保该类型只有一个实例

时间:2019-03-28 00:55:04

标签: java oop composite

我遵循以下示例:
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

例如,如果它为同一类型两次调用添加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);
    }

如果Department的机构是第一个,我也希望保留订单,我希望将其保持为1,这意味着它应该在financialDepartment之前打印salesDepartment3

1 个答案:

答案 0 :(得分:2)

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

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