1 usingSystem;2 3 namespaceComposite4 {5 /// <summary> 6 ///Bzyzhang7 ///time: 2016/5/30 7:11:108 ///Blog Address:http://www.cnblogs.com/bzyzhang/9 ///Component Description: This code is copyright Bzyzhang all, use must bring Bzyzhang blog addressTen /// </summary> One Public Abstract classComponent A { - protected stringname; - the PublicComponent (stringname) - { - This. Name =name; - } + - Public Abstract voidAdd (Component c); + Public Abstract voidRemove (Component c); A Public Abstract voidDisplay (intdepth); at } -}View Code
1 usingSystem;2 3 namespaceComposite4 {5 /// <summary> 6 ///Bzyzhang7 ///time: 2016/5/30 7:13:288 ///Blog Address:http://www.cnblogs.com/bzyzhang/9 ///Leaf Description: This code copyright belongs to Bzyzhang All, use must bring Bzyzhang blog addressTen /// </summary> One Public classleaf:component A { - PublicLeaf (stringname) -:Base(name) the { - } - - Public Override voidAdd (Component c) + { -Console.WriteLine ("cannot add to a leaf"); + } A at Public Override voidRemove (Component c) - { -Console.WriteLine ("cannot remove from a leaf"); - } - - Public Override voidDisplay (intdepth) in { -Console.WriteLine (New string('-', depth) +name); to } + } -}View Code
1 usingSystem;2 usingSystem.Collections.Generic;3 4 namespaceComposite5 {6 /// <summary> 7 ///Bzyzhang8 ///time: 2016/5/30 7:15:499 ///Blog Address:http://www.cnblogs.com/bzyzhang/Ten ///Composite Description: This code is copyright Bzyzhang all, use must bring Bzyzhang blog address One /// </summary> A Public classcomposite:component - { - Privatelist<component> children =NewList<component>(); the - PublicComposite (stringname) -:Base(name) - { + } - + Public Override voidAdd (Component c) A { at children. ADD (c); - } - - Public Override voidRemove (Component c) - { - children. Remove (c); in } - to Public Override voidDisplay (intdepth) + { -Console.WriteLine (New string('-', depth) +name); the foreach(Component Componentinchchildren) * { $Component. Display (Depth +2);Panax Notoginseng } - } the } +}View Code
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 7 namespaceComposite8 {9 class ProgramTen { One Static voidMain (string[] args) A { -Composite root =NewComposite ("Root"); -Root. ADD (NewLeaf ("Leaf A")); theRoot. ADD (NewLeaf ("Leaf B")); - -Composite Comp =NewComposite ("Composite X"); -Comp. ADD (NewLeaf ("Leaf XA")); +Comp. ADD (NewLeaf ("Leaf XB")); - + Root. ADD (comp); A atComposite COMP2 =NewComposite ("Composite XY"); -Comp2. ADD (NewLeaf ("Leaf XYA")); -Comp2. ADD (NewLeaf ("Leaf XYB")); - - Root. ADD (COMP2); - inRoot. ADD (NewLeaf ("Leaf C")); - toLeaf leaf =NewLeaf ("Leaf D"); + Root. Add (leaf); - Root. Remove (leaf); the *Root. Display (1); $ }Panax Notoginseng } -}View Code
Design Pattern Learning Notes--combination mode