设计模式之组合模式
目录
- 定义
- 结构
- 适用场景
- 使用示例
定义
将对象组织成树状层次,通过统一的接口(如Component)管理所有节点(包括叶子节点和容器节点)。叶子节点处理基础操作,容器节点负责组合子节点并递归调用操作。
结构
适用场景
1、当系统需处理嵌套层级不固定的对象关系时,组合模式通过抽象接口统一叶子节点(基础单元)和容器节点(组合单元)
2、统一操作复杂对象集合(递归行为需求),对嵌套结构执行跨层级操作时,组合模式屏蔽节点类型差异,简化递归逻辑
3、简化客户端调用逻辑(接口一致性),当业务要求忽略节点差异时,组合模式提供透明性。
使用示例
以电商商品分类系统价格计算为例。
定义抽象构件
/*** 抽象构件(商品节点接口)*/
public interface ProductComponent {default void add(ProductComponent item) {throw new UnsupportedOperationException();}double getPrice(); // 统一方法:计算价格default void remove(ProductComponent item) {throw new UnsupportedOperationException();}}
定义叶子节点
/*** 叶子构件(具体商品)*/
public class Product implements ProductComponent {@Getterprivate String name;private final double price;public Product(String name, double price) {this.name = name;this.price = price;}@Overridepublic double getPrice() {return price;}}
定义容器节点
/*** 容器构件(商品分类)*/
public class ProductCategory implements ProductComponent {@Getterprivate final String name;private final List<ProductComponent> items = new ArrayList<>();public ProductCategory(String name) {this.name = name;}@Overridepublic void add(ProductComponent item) {items.add(item);}@Overridepublic void remove(ProductComponent item) {items.remove(item);}@Overridepublic double getPrice() {double total = 0;for (ProductComponent item : items) {total += item.getPrice(); // 递归计算子节点价格}return total;}}
测试
public class Client {public static void main(String[] args) {ProductComponent electronics = new ProductCategory("电子产品");electronics.add(new Product("手机", 2999));electronics.add(new Product("耳机", 399));ProductComponent bundle = new ProductCategory("套装");bundle.add(new Product("充电器", 99));bundle.add(electronics); // 嵌套组合System.out.println(bundle.getPrice()); // 输出:3497}}