组合模式(Composite Pattern)是一种设计模式,它允许将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得客户端可以统一处理单个对象和组合对象,而无需区分它们的差异。
在Java中,组合模式可以通过以下方式实现:
1. 创建一个抽象类或接口(Component),定义了组合对象和叶子对象的共同行为。组合对象可以包含其他组合对象或叶子对象。
2. 创建一个叶子类(Leaf),实现了Component接口,并表示组合中的叶子对象。叶子对象没有子对象。
3. 创建一个组合类(Composite),实现了Component接口,并表示组合中的组合对象。组合对象可以包含其他组合对象或叶子对象。组合类通常会维护一个子对象的列表。
以下是一个简单的示例代码,演示了如何使用组合模式:
- // 抽象类或接口
- abstract class Component {
- protected String name;
-
- public Component(String name) {
- this.name = name;
- }
-
- public abstract void operation();
- }
-
- // 叶子类
- class Leaf extends Component {
- public Leaf(String name) {
- super(name);
- }
-
- @Override
- public void operation() {
- System.out.println("Leaf " + name + " operation");
- }
- }
-
- // 组合类
- class Composite extends Component {
- private List
components = new ArrayList<>(); -
- public Composite(String name) {
- super(name);
- }
-
- public void addComponent(Component component) {
- components.add(component);
- }
-
- public void removeComponent(Component component) {
- components.remove(component);
- }
-
- @Override
- public void operation() {
- System.out.println("Composite " + name + " operation");
-
- for (Component component : components) {
- component.operation();
- }
- }
- }
-
- // 客户端
- public class Main {
- public static void main(String[] args) {
- Component leaf1 = new Leaf("Leaf 1");
- Component leaf2 = new Leaf("Leaf 2");
-
- Composite composite1 = new Composite("Composite 1");
- composite1.addComponent(leaf1);
- composite1.addComponent(leaf2);
-
- Component leaf3 = new Leaf("Leaf 3");
-
- Composite composite2 = new Composite("Composite 2");
- composite2.addComponent(leaf3);
- composite2.addComponent(composite1);
-
- composite2.operation();
- }
- }
在这个示例中,Component是抽象类或接口,定义了组合对象和叶子对象的共同行为。Leaf类是叶子类,实现了Component接口,并表示组合中的叶子对象。Composite类是组合类,实现了Component