在 Java 中,组合模式(Composite Pattern)本身是一个结构型设计模式,用于统一处理“单个对象”和“对象容器”。但在实际使用中,常常会出现性能、扩展性、安全性、可读性等问题。下面从「常见痛点 → 优化思路 → 示例代码」系统讲一下如何优化。
interface Component {
void add(Component c);
void remove(Component c);
void operation();
}
叶子也被迫实现 add/remove
abstract class Component {
abstract void operation();
}
class Leaf extends Component {
void operation() { }
}
class Composite extends Component {
private List<Component> children = new ArrayList<>();
void add(Component c) { children.add(c); }
void operation() {
children.forEach(Component::operation);
}
}
✅ 优点:
void traverse(Component root) {
Deque<Component> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
Component c = stack.pop();
c.operation();
if (c instanceof Composite) {
((Composite) c).getChildren().forEach(stack::push);
}
}
}
class Composite {
private volatile Integer cache;
int getPrice() {
if (cache == null) {
cache = children.stream()
.mapToInt(Component::getPrice)
.sum();
}
return cache;
}
void invalidate() {
cache = null;
children.forEach(Component::invalidate);
}
}
✅ 适合:
避免手动 new + add 的混乱
Composite root = Composite.builder()
.add(new Leaf())
.add(Composite.builder()
.add(new Leaf())
.build())
.build();
✅ 优点:
组合模式容易“逻辑堆在节点里”
interface Visitor {
void visit(Leaf l);
void visit(Composite c);
}
class PrintVisitor implements Visitor {
public void visit(Leaf l) { }
public void visit(Composite c) { }
}
✅ 好处:
final class Composite {
private final List<Component> children;
Composite(List<Component> children) {
this.children = List.copyOf(children);
}
}
✅ 适合:
❌ 结构不稳定
❌ 深度极小(2~3 层)
❌ 性能极度敏感(用扁平结构)
| 优化点 | 做法 |
|---|---|
| 类型安全 | Leaf / Composite 分离 |
| 性能 | 栈遍历 + 缓存 |
| 可读性 | Builder 构建 |
| 扩展性 | Visitor 模式 |
| 并发 | 不可变对象 |
如果你愿意,可以:
我可以帮你针对性重构 + 性能对比。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。