设计模式-组合模式

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

相关推荐
程序员Terry1 天前
同事被深拷贝坑了3小时,我教他原型模式的正确打开方式
java·设计模式
刀法如飞2 天前
AI时代,程序员都应该是算法思想工程师
人工智能·设计模式·程序员
在西安放羊的牛油果2 天前
我把 2000 行下单代码,重构成了一套交易前端架构
前端·设计模式·架构
寅时码3 天前
React 正在演变为一场不可逆的赛博瘟疫:AI 投毒、编译器迷信与装死的官方
前端·react.js·设计模式
willow6 天前
Axios由浅入深
设计模式·axios
七月丶8 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞8 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼8 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟9 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式