设计模式-组合模式

组合模式(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<Component> 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

相关推荐
敲代码的 蜡笔小新5 小时前
【行为型之策略模式】游戏开发实战——Unity灵活算法架构的核心实现策略
unity·设计模式·c#·策略模式
_yingty_5 小时前
Java设计模式-策略模式(行为型)
java·设计模式·策略模式
炎芯随笔15 小时前
【C++】【设计模式】生产者-消费者模型
开发语言·c++·设计模式
workflower1 天前
使用谱聚类将相似度矩阵分为2类
人工智能·深度学习·算法·机器学习·设计模式·软件工程·软件需求
枣伊吕波1 天前
第六节第二部分:抽象类的应用-模板方法设计模式
android·java·设计模式
lalajh1 天前
论软件设计模式及其应用
设计模式
lgily-12251 天前
常用的设计模式详解
java·后端·python·设计模式
周努力.2 天前
设计模式之中介者模式
设计模式·中介者模式
yangyang_z3 天前
【C++设计模式之Template Method Pattern】
设计模式
源远流长jerry3 天前
常用设计模式
设计模式