组合模式(解决 树形 ,局部与整体关系)

组合模式:

将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

说白了,就是组合树形结构,针对树形结构的每个节点,拥有的行为几乎是相同的,除了叶子节点没有子节点外。

用途:如公司的组织架构。

 

一、UML结构图

 

 

二、示例代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 组合模式
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             Component root = new Composite("Root");
13 
14             Component d1 = new Composite("Dept1");
15             Component d1_1=new Leaf("leaf1");
16             Component d1_2 = new Leaf("leaf2");
17             d1.Add(d1_1);
18             d1.Add(d1_2);
19             root.Add(d1);
20 
21             Component d2 = new Composite("Dept2");
22             Component d2_1 = new Leaf("leaf3");
23             Component d2_2 = new Leaf("leaf4");
24             d2.Add(d2_1);
25             d2.Add(d2_2);
26             root.Add(d1);
27 
28             root.Display(1);
29 
30             Console.Read();
31 
32         }
33     }
34 
35     /// <summary>
36     /// 组建类
37     /// </summary>
38     public abstract class Component
39     {
40         protected string m_Name;
41         public Component(string name)
42         {
43             m_Name = name;
44         }
45 
46         public abstract void Add(Component c);
47         public abstract void Remove(Component c);
48         public abstract void Display(int depth);
49     }
50 
51     public class Leaf : Component
52     {
53         public Leaf(string name) : base(name) { }
54 
55         public override void Add(Component c)
56         {
57             Console.WriteLine("不能添加组件。");
58         }
59         public override void Remove(Component c)
60         {
61             Console.WriteLine("不能移出组件。");
62         }
63 
64         public override void Display(int depth)
65         {
66             Console.WriteLine(new string('-', depth)+m_Name);
67         }
68     }
69 
70     public class Composite : Component
71     {
72         public Composite(string name)
73             : base(name)
74         {
75 
76         }
77 
78         private List<Component> lstComponent = new List<Component>();
79 
80         public override void Add(Component c)
81         {
82             if(c!=null)
83             lstComponent.Add(c);
84         }
85         public override void Remove(Component c)
86         {
87             if (c != null && lstComponent.Contains(c))
88                 lstComponent.Remove(c);
89         }
90         public override void Display(int depth)
91         {
92             Console.WriteLine(new string('-', depth) + m_Name);
93             foreach (Component c in lstComponent)
94                 c.Display(depth+2);
95         }
96     }
97 
98 }
示例代码

 运行效果:

 

 

 

三、应用

如.net中的TreeView控件、用户自定义控件等。

用户自定义控件,可以包含多个基本控件(如两个文本框+Button按钮,组成一个登陆控件),其属性和基本控件几乎相同。

 

 

posted @ 2019-12-02 20:25  秋飘  阅读(298)  评论(0编辑  收藏  举报