设计模式-组合模式

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

相关推荐
Carl_奕然3 小时前
【智能体】Agent的四种设计模式之:ReAct
人工智能·设计模式·语言模型
二哈赛车手4 小时前
新人笔记---多策略搭建策略执行链实现RAG检索后过滤
java·笔记·spring·设计模式·ai·策略模式
楼田莉子5 小时前
仿Muduo的高并发服务器:Channel模块与Poller模块
linux·服务器·c++·学习·设计模式
geovindu20 小时前
go: Strategy Pattern
开发语言·设计模式·golang·策略模式
嵌入式学习_force1 天前
02_state
设计模式·蓝牙
qcx231 天前
Warp源码深度解析(七):Token预算策略——双轨计费、上下文溢出与摘要压缩
人工智能·设计模式·rust·wrap
Cosolar2 天前
提示词工程面试题系列 - Zero-Shot Prompting 和 Few-Shot Prompting 的核心区别是什么?
人工智能·设计模式·架构
geovindu2 天前
go:Template Method Pattern
开发语言·后端·设计模式·golang·模板方法模式
钝挫力PROGRAMER2 天前
贫血模型的改进
java·开发语言·设计模式·架构
qcx232 天前
Warp源码深度解析(二):自研GPU UI框架——WarpUI的ECH模式与渲染管线
人工智能·ui·设计模式·rust