++组合模式是指将一组相似对象当做一个单一对象的设计模式.++
++1.组成角色:++
++1.1组件:++
++组合中的对象声明接口,主要用于访问和管理其子组件.++
++1.2叶子节点:++
++定义组合中原始对象行为的类.叶子节点表示组合中的叶对象.++
++1.3组合:++
++又称为容器,存储子组件并在组件接口中实现与子组件有关的类.++
++1.4客户端:++
++客户端可以通过组件接口操作组合中的对象.以及与树形结构中的所有项目交互.++
++2.使用场景:++
++2.1需要忽略组合对象和单个对象之间差异时.++
++2.2需要实现树形结构时.++
++2.3客户端以统一的方式处理简单或复杂的元素.++
3.实现:
3.1组件接口:
Go
// 组件接口
type Component interface {
Execute()
}
3.2叶节点类:
Go
// 叶子节点类
type Leaf struct {
value int
}
// 创建一个新的叶节点对象
func NewLeaf(value int) *Leaf {
return &Leaf{value: value}
}
// 打印叶节点的值
func (l *Leaf) Execute() {
fmt.Println(l.value)
}
3.3组合类:
Go
// 组合类
type Composite struct {
children []Component
}
// 创建一个新的组合对象
func NewComposite() *Composite {
return &Composite{make([]Component, 0)}
}
3.4组合类中添加方法:
Go
// 添加方法
func (c *Composite) Add(component Component) {
c.children = append(c.children, component)
}
func (c *Composite) Execute() {
for _, child := range c.children {
child.Execute()
}
}
3.5客户端:
Go
func main() {
composite := itboStudy.NewComposite()
leaf := itboStudy.NewLeaf(99)
leaf1 := itboStudy.NewLeaf(88)
leaf2 := itboStudy.NewLeaf(77)
composite.Add(leaf)
composite.Add(leaf1)
composite.Add(leaf2)
composite.Execute()
}
4.实战:
4.1叶子节点:
Go
// 叶子节点类
type Files struct {
Name string
}
func (f *Files) Search(name string) {
fmt.Printf("在文件%s中递归搜索%s", f.Name, name)
}
func (f *Files) GetName() string {
return f.Name
}
4.2组合类:
Go
// 定义组合类.
type Folders struct {
Compents []Components
Name string
}
func (f *Folders) Search(name string) {
fmt.Printf("在文件%s中递归搜索%s", f.Name, name)
for i := range f.Compents {
f.Compents[i].Search(name)
}
}
func (f *Folders) Add(c Components) {
f.Compents = append(f.Compents, c)
}
4.3组件接口:
Go
// 定义组件接口
type Components interface {
Search(name string)
}
4.4客户端:
Go
func main() {
file1 := &itboStudy.Files{Name: "itboStudy1"}
file2 := &itboStudy.Files{Name: "itboStudy2"}
file3 := &itboStudy.Files{Name: "itboStudy3"}
folders := &itboStudy.Folders{Name: "itboFolder"}
folders.Add(file1)
folders.Add(file2)
folders.Add(file3)
folders.Search("99")
}
++5.优点:++
++无须了解构成树形结构的对象具体类,只需要调用接口方法.++
++客户端可以使用组件对象与复合结构中的对象进行交互.++
++如果调用的是叶子节点对象,可以直接处理请求.++
++如果调用的组合对象,组合模式会把请求转发给子组件.++
++6.缺点:++
++一旦定义了树结构,设计会过于笼统.++
++组合模式很难将树的组件限制为特定类型.++
++为了强制执行这种约束,程序必须依赖运行时检查.组合模式不能使用编程语言的类型系统.++
++士别三日当刮目相待.++