问题
- 多级树形菜单
- 文件和文件夹目录
我们创建一个简单的对象组合成复杂的对象,然后复杂的对象与简单的对象组合生成一个更复杂的对象,同时客户端代码必须对简单对象与复杂对象进行区分,但是实际大多数情况下用户认为它们是一样的。但是对这些类区别使用,使得程序更加复杂。
组合模式
概述
组合模式也叫合成模式,有时又叫做部分-整体模式,他在应对树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以向处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。
分类
- 将管理子元素的方法定义在Composite类中
- 将管理子元素的方法定义在Component接口中,这样Leaf类就需要对这些方法空实现。

模式的组成
抽象角色对象(Component): 定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性。
树叶结构对象(Leaf): 下再也没有其他的分支,也就是遍历的最小单位。
树枝结构对象(Composite): 它的作用是组合树枝节点和叶子节点形成一个树形结构。
客户角色(Client):通过component接口操纵组合部件的对象。
// 抽象角色对象
@interface Component : NSObject
- (instancetype)initWithName:(NSString *)name;
- (void)add:(Component *)components;
- (void)remove:(Component *)components;
- (NSString *)name;
@end
// 树叶结构
@interface Leaf : Component
@end
@implementation Leaf {
NSString *_name;
}
- (instancetype)initWithName:(NSString *)name {
if (self) {
_name = name;
}
return self;
}
- (void)add:(Component *)components {
}
- (void)remove:(Component *)components {
}
- (NSString *)name {
return _name;
}
@end
// 树枝结构
@interface Composite : Components
@end
@implementation Composite {
NSString *_name;
NSMutableArray *_array;
}
- (instancetype)initWithName:(NSString *)name {
if (self) {
_name = name;
_array = [NSMutableArray new];
}
return self;
}
- (void)add:(Component *)components {
[_array addObject:components];
}
- (void)remove:(Component *)components {
[_array removeObject:components];
}
- (NSString *)name {
return _name;
}
@end
// 客户角色
@implementation Client
- (void)display {
Composite *c1 = [[Composite alloc] initWithName:@"C1"];
Composite *c2 = [[Composite alloc] initWithName:@"C2"];
Composite *c3 = [[Composite alloc] initWithName:@"C3"];
Composite *c4 = [[Composite alloc] initWithName:@"C4"];
Leaf *l1 = [[Leaf alloc] initWithName:@"L1"];
Leaf *l2 = [[Leaf alloc] initWithName:@"L2"];
Leaf *l3 = [[Leaf alloc] initWithName:@"L3"];
Leaf *l4 = [[Leaf alloc] initWithName:@"L4"];
[c1 add:l1];
[c1 add:l2];
[c3 add:l3];
NSArray<Component *> *components = [NSArray arrayWithObjects:c2,c3,c4,l4, nil];
for (Component *component in components) {
NSLog(@"%@",[component name]);
}
}
@end
总结
组合模式解耦了客户程序与复杂元素内部结构,从而使客户程序可以向处理简单元素一样来处理复杂元素。