设计模式-组合模式

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

相关推荐
阿闽ooo5 小时前
外观模式:从家庭电源控制看“简化接口“的设计智慧
c++·设计模式·外观模式
Geoking.7 小时前
【UML】面向对象中类与类之间的关系详解
设计模式·uml
希望_睿智13 小时前
实战设计模式之中介者模式
c++·设计模式·架构
有一个好名字18 小时前
设计模式-观察者模式
观察者模式·设计模式
青柠代码录19 小时前
【设计模式】A1-单例模式
单例模式·设计模式
阿闽ooo1 天前
深入浅出适配器模式:从跨国插头适配看接口兼容的艺术
c++·设计模式·适配器模式
Kiyra1 天前
WebSocket vs HTTP:为什么 IM 系统选择长连接?
分布式·websocket·网络协议·http·设计模式·系统架构·wpf
山沐与山1 天前
【设计模式】Python责任链模式:从入门到实战
python·设计模式·责任链模式
繁星星繁2 天前
【项目】基于SDK实现的智能聊天助手(使用api接入deepseek)------(二)
c++·设计模式·学习方法