经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » 设计模式 » 查看文章
Composite组合模式
来源:cnblogs  作者:大师兄石头  时间:2021/2/18 15:34:44  对本文有异议

>>返回《C#常用设计模式》

1. 简介

  • 定义
    • 组合多个对象形成树形结构以表示具有部分-整体关系的层次结构。
    • 组合模式让调用程序可以统一对待单个对象和组合对象
  • 案例
    • 例如文件系统的文件夹和文件结构就是此模式
    • winform中,空间的基类是Control类型,子类有的是单一类型(Textbox),有的是容器类型(Panel),Add和Remove方法使用暴露Collections的方式,都有方法(eachChild)

2. 示例

  1. namespace WindowsFormsApplication1
  2. {
  3. //抽象的部件类描述将来所有部件共有的行为
  4. public abstract class Component
  5. {
  6. protected string name;
  7. public string Name
  8. {
  9. get
  10. {
  11. return name;
  12. }
  13. set
  14. {
  15. name = value;
  16. }
  17. }
  18. //添加部件
  19. public abstract void Add(Component component);
  20. //删除部件
  21. public abstract void Remove(Component component);
  22. //遍历所有子部件
  23. public abstract void eachChild();
  24. }
  25. //组合部件类
  26. public class Leaf : Component
  27. {
  28. //叶子节点不具备添加的能力,所以不实现
  29. public override void Add(Component component)
  30. {
  31. throw new NotImplementedException();
  32. }
  33. //叶子节点不具备添加的能力必然也不能删除
  34. public override void Remove(Component component)
  35. {
  36. throw new NotImplementedException();
  37. }
  38. //叶子节点没有子节点所以显示自己的执行结果
  39. public override void eachChild()
  40. {
  41. Console.WriteLine("{0}执行了..", name);
  42. }
  43. }
  44. //组合类
  45. public class Composite : Component
  46. {
  47. //用来保存组合的部件
  48. List<Component> myList = new List<Component>();
  49. //添加节点 添加部件
  50. public override void Add(Component component)
  51. {
  52. myList.Add(component);
  53. }
  54. //删除节点 删除部件
  55. public override void Remove(Component component)
  56. {
  57. myList.Remove(component);
  58. }
  59. //遍历子节点
  60. public override void eachChild()
  61. {
  62. Console.WriteLine("{0}执行了..", name);
  63. foreach (Component c in myList)
  64. {
  65. c.eachChild();
  66. }
  67. }
  68. }
  69. class Client
  70. {
  71. static void Main(string[] args)
  72. {
  73. //构造根节点
  74. Composite rootComponent = new Composite();
  75. rootComponent.Name = "根节点";
  76. //添加两个叶子几点,也就是子部件
  77. Leaf l = new Leaf();
  78. l.Name = "叶子节点一";
  79. Leaf l1 = new Leaf();
  80. l1.Name = "叶子节点二";
  81. rootComponent.Add(l);
  82. rootComponent.Add(l1);
  83. //遍历组合部件
  84. rootComponent.eachChild();
  85. }
  86. }
  87. }

3. 适用环境

  • 在具有整体和部分层次的结构中,希望通过一种方式忽略整体与部分的差异一致的对待它们
  • 在一个使用面向对象语言开发的系统中要处理一个树形结构
  • 在一个系统总能够分离出叶子容器对象,而且它们的类型不固定,需要增加一些新的类型

原文链接:http://www.cnblogs.com/BigBrotherStone/p/composite.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号