VS 2008

组合模式使得我们可以以同样的方式看待单一Comonent和Component集合。
也就是,单一对象和该对象的组合具有相同的抽象行为。
组合模式通常用于构建树型结构。

1. 模式UML图
    
    Core Design Patterns(4) Composite 组合模式

2. 应用
    
    项目中有一组部门信息,部门之间具有父子关系,是一个典型的树型结构,如有一个部门叫市政局,下属有市管处、公路处两个部门,公路处下属又有公路署部门等等。

Core Design Patterns(4) Composite 组合模式

Department.cs
Core Design Patterns(4) Composite 组合模式using System;
Core Design Patterns(4) Composite 组合模式
using System.Collections.Generic;
Core Design Patterns(4) Composite 组合模式
using System.Linq;
Core Design Patterns(4) Composite 组合模式
using System.Text;
Core Design Patterns(4) Composite 组合模式
}

IDepartment.cs
Core Design Patterns(4) Composite 组合模式using System;
Core Design Patterns(4) Composite 组合模式
using System.Collections.Generic;
Core Design Patterns(4) Composite 组合模式
using System.Linq;
Core Design Patterns(4) Composite 组合模式
using System.Text;
Core Design Patterns(4) Composite 组合模式

DepartmentLeaf.cs
Core Design Patterns(4) Composite 组合模式using System;
Core Design Patterns(4) Composite 组合模式
using System.Collections.Generic;
Core Design Patterns(4) Composite 组合模式
using System.Linq;
Core Design Patterns(4) Composite 组合模式
using System.Text;
Core Design Patterns(4) Composite 组合模式
}

DepartmentComposite.cs
Core Design Patterns(4) Composite 组合模式using System;
Core Design Patterns(4) Composite 组合模式
using System.Collections.Generic;
Core Design Patterns(4) Composite 组合模式
using System.Linq;
Core Design Patterns(4) Composite 组合模式
using System.Text;
Core Design Patterns(4) Composite 组合模式
}

Client
Core Design Patterns(4) Composite 组合模式using System;
Core Design Patterns(4) Composite 组合模式
using System.Collections.Generic;
Core Design Patterns(4) Composite 组合模式
using System.Linq;
Core Design Patterns(4) Composite 组合模式
using System.Text;
Core Design Patterns(4) Composite 组合模式
using DesignPattern.Composite.BLL;
Core Design Patterns(4) Composite 组合模式
}

Output
Core Design Patterns(4) Composite 组合模式

3. 思考
    
    对于组合模式,通常可以将前述的UML进行退还,我们甚至可以不要Leaf类,为了灵活扩展性,每个叶子都可以演变为树枝。
    对于本例的部门树型结构其实只是选择了一个最简单的行为进行实现,真正的树,需要实现的行为还远不止这些。

相关文章:

  • 2021-10-04
  • 2021-08-30
  • 2022-02-21
  • 2022-01-03
  • 2021-10-28
  • 2022-02-27
  • 2022-01-30
猜你喜欢
  • 2021-11-17
  • 2021-12-01
  • 2022-12-23
  • 2022-01-22
  • 2021-11-05
  • 2021-06-26
  • 2021-12-12
相关资源
相似解决方案