gpt4 book ai didi

java - 如何在同一类的其他对象中设置同一类对象

转载 作者:行者123 更新时间:2023-12-01 18:53:06 25 4
gpt4 key购买 nike

我想优化这段代码,因为我可以有多个 parent 和 child (在 hibernate 中 self 加入)。我希望一些家长能够照顾 child 。例如,事件是一个父事件,它可能有第 n 个子事件,例如编辑、创建、更新、删除。而像 Deals、Movies 和 Resturant 这样的一些家长可能有 child ,也可能没有。有没有办法编写通用代码

        Privilege parent = new Privilege("Event");
Privilege parent1 = new Privilege("Deals");
Privilege parent2 = new Privilege("Movies");
Privilege parent3 = new Privilege("Restaurant");

Privilege parent4 = new Privilege("Outdoor");

Privilege child = new Privilege("Create");
child.setParentId(parent);

Privilege child1 = new Privilege("Edit");
child1.setParentId(parent);

Privilege child2 = new Privilege("Update");
child2.setParentId(parent);
Privilege child3 = new Privilege("Delete");
child3.setParentId(parent);

最佳答案

您可以创建这样的函数来设置权限

private static List<Privilege> setPrivileges() {

Privilege parent = setParentPrivilege("Event");
Privilege parent1 = setParentPrivilege("Deals");
Privilege parent2 = setParentPrivilege("Movies");
Privilege parent3 = setParentPrivilege("Restaurant");
Privilege parent4 = setParentPrivilege("Outdoor");

Privilege child = setFirstLevel(parent, "Create");
Privilege child1 = setFirstLevel(parent, "Edit");
Privilege child2 = setFirstLevel(parent, "Update");
Privilege child3 = setFirstLevel(parent, "Delete");
Privilege subchild1 = setSecondLevel(child3,"Sub Delete");

return Collections.unmodifiableList(
Arrays.asList(
parent,
parent1,
parent2,
parent3,
parent4,
child,
child1,
child2,
child3,
subchild1
));
}

private static Privilege setParentPrivilege(String name) {
return new Privilege(name);
}

private static Privilege setFirstLevel(Privilege firstLevel, String name) {
Privilege firstLevelChild = setParentPrivilege(name);
firstLevelChild.setParentId(firstLevel);
return firstLevelChild;
}

private static Privilege setSecondLevel(Privilege secondLevel, String name) {
Privilege secondLevelChild = new Privilege(name);
secondLevelChild.setParentId(secondLevel);
return secondLevelChild;
}

关于java - 如何在同一类的其他对象中设置同一类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59700602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com