⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 compositestructural.cs

📁 使用C#程序将23个常用设计模式进行列表显示
💻 CS
字号:
using System;
using System.Windows.Forms;
using System.Collections;

namespace DesignPattern.CompositeStructural
{
    class CompositeStructural : AbstractPattern
    {
        public static void Run(TextBox tbInfo)
        {
            s_tbInfo = tbInfo;
            s_tbInfo.Text = "";

            // Create a tree structure 
            Composite root = new Composite("root"); 
            root.Add(new Leaf("Leaf A")); 
            root.Add(new Leaf("Leaf B")); 
            
            Composite comp = new Composite("Composite X"); 
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB")); 

            root.Add(comp); 
            root.Add(new Leaf("Leaf C")); 
            
            // Add and remove a leaf 
            Leaf leaf = new Leaf("Leaf D"); 
            root.Add(leaf); 
            root.Remove(leaf); 
            
            // Recursively display tree 
            root.Display(1); 
            
            // Wait for user 
            //Console.Read();
        }
    }
    
    // "Component" 
    abstract class Component 
    {
        protected string name; 
        // Constructor 
        public Component(string name) 
        {
            this.name = name; 
        }
        public abstract void Add(Component c); 
        public abstract void Remove(Component c); 
        public abstract void Display(int depth); 
    }
    
    // "Composite" 
    class Composite : Component 
    {
        private ArrayList children = new ArrayList();
        // Constructor 
        public Composite(string name) : base(name) 
        {
        } 
        
        public override void Add(Component component) 
        {
            children.Add(component); 
        }
        public override void Remove(Component component) 
        {
            children.Remove(component); 
        }
        public override void Display(int depth) 
        {
            DesignPattern.FormMain.OutputInfo(new String('-', depth) + name); 
            // Recursively display child nodes 
            foreach (Component component in children) 
            { 
                component.Display(depth + 2); 
            }
        }
    }
    
    // "Leaf" 
    class Leaf : Component
    {
        // Constructor 
        public Leaf(string name)
            : base(name)
        {
        }
        public override void Add(Component c)
        {
            DesignPattern.FormMain.OutputInfo("Cannot add to a leaf");
        }
        public override void Remove(Component c)
        {
            DesignPattern.FormMain.OutputInfo("Cannot remove from a leaf");
        }
        public override void Display(int depth)
        {
            DesignPattern.FormMain.OutputInfo(new String('-', depth) + name);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -