组合模式(Composite Pattern)是一种结构型设计模式,它允许你将对象组合成树形结构来表示“部分-整体”的层次结构。组合模式使得客户端可以统一地处理单个对象和对象的组合。
在Java中,组合模式通常涉及以下几个角色:
下面是一个简单的Java组合模式实现示例:
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
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);
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void display(int depth) {
System.out.println("-" + "-".repeat(depth) + name);
}
}
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
private List<Component> children = new ArrayList<>();
public Composite(String name) {
super(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);
}
}
}
public class Client {
public static void main(String[] args) {
// 创建根节点
Composite root = new Composite("Root");
// 创建叶子节点
Leaf leaf1 = new Leaf("Leaf 1");
Leaf leaf2 = new Leaf("Leaf 2");
// 创建树枝节点
Composite branch1 = new Composite("Branch 1");
Leaf leaf3 = new Leaf("Leaf 3");
Leaf leaf4 = new Leaf("Leaf 4");
// 构建树形结构
root.add(branch1);
root.add(leaf1);
root.add(leaf2);
branch1.add(leaf3);
branch1.add(leaf4);
// 显示树形结构
root.display(0);
}
}
在这个示例中,Component 是抽象构件,Leaf 是叶子构件,Composite 是树枝构件。客户端代码创建了一个树形结构并显示它。组合模式使得客户端可以统一地处理单个对象和对象的组合,而不需要关心它们的具体类型。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。