您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
组合模式(Composite Pattern)是一种结构型设计模式,它允许你将对象组合成树形结构来表示“部分-整体”的层次结构。组合模式使得客户端可以统一地对待单个对象和对象的组合。
在Java中,组合模式通常涉及以下几个角色:
下面是一个简单的Java实例,演示了如何使用组合模式:
// Component
abstract class Component {
public void add(Component component) {
throw new UnsupportedOperationException();
}
public void remove(Component component) {
throw new UnsupportedOperationException();
}
public Component getChild(int index) {
throw new UnsupportedOperationException();
}
public abstract void display(int depth);
}
// Leaf
class Leaf extends Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
public void display(int depth) {
System.out.println("-" + "-".repeat(depth) + name);
}
}
// Composite
class Composite extends Component {
private List<Component> children = new ArrayList<>();
private String name;
public Composite(String name) {
this.name = name;
}
@Override
public void add(Component component) {
children.add(component);
}
@Override
public void remove(Component component) {
children.remove(component);
}
@Override
public Component getChild(int index) {
return children.get(index);
}
@Override
public void display(int depth) {
System.out.println("-" + "-".repeat(depth) + name);
for (Component child : children) {
child.display(depth + 2);
}
}
}
// Client
public class Client {
public static void main(String[] args) {
// 创建根节点
Composite root = new Composite("Root");
// 创建叶子节点
Leaf leaf1 = new Leaf("Leaf1");
Leaf leaf2 = new Leaf("Leaf2");
// 创建子树
Composite subtree1 = new Composite("Subtree1");
Leaf leaf3 = new Leaf("Leaf3");
Leaf leaf4 = new Leaf("Leaf4");
subtree1.add(leaf3);
subtree1.add(leaf4);
// 将叶子节点和子树添加到根节点
root.add(leaf1);
root.add(leaf2);
root.add(subtree1);
// 显示整个树结构
root.display(1);
}
}
在这个例子中,我们定义了一个抽象类Component
,它包含了添加、删除和获取子节点的方法,以及一个抽象的display
方法用于显示节点。Leaf
类表示叶子节点,它实现了display
方法来显示自己的名称。Composite
类表示树枝节点,它可以包含其他组件,并实现了add
、remove
和getChild
方法来管理子节点,同时它的display
方法会递归地显示所有子节点。
客户端代码创建了一个树形结构,并通过调用display
方法来显示整个结构。这个例子展示了如何使用组合模式来统一处理单个对象和对象组合。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。