使用场景
图形界面库:在图形界面开发中,UI 元素(按钮、文本框等)和容器元素(面板、窗口等)可以使用组合模式来构建复杂的用户界面。这样,可以统一处理单个元素和组合元素,使得客户端代码更简洁
文件系统和目录结构:文件系统是一个经典的组合模式应用场景。文件夹可以包含文件和其他文件夹,形成一个树形结构。通过组合模式,可以一致地处理文件和文件夹,而不必在客户端代码中区分它们
组织架构和人员管理:在组织架构中,部门可以包含员工和其他部门,形成一个层次结构。通过组合模式,可以一致地管理单个员工和组合部门,简化组织管理的代码。
菜单和菜单项:菜单系统通常包含菜单项和子菜单,可以使用组合模式来构建菜单层次结构。这样,可以一致地处理单个菜单项和包含子菜单的菜单
----实现指令菜单模式,新建ICommand.cs(接口),Command.cs(子叶),CommandManage.cs(复合叶),main窗体
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinFormsApp8 { internal interface ICommand { Guid Guid { get; set; } String Name { get; set; } void Execute(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinFormsApp8 { internal class Command : ICommand { private Guid _guid; private string _name; Guid ICommand.Guid { get => _guid; set => _guid = value; } string ICommand.Name { get => _name; set => _name = value; } public void Execute() { _action(); } private Action _action; public Command(string guid,string name, Action action) { _guid = new Guid(guid); _name= name; _action = action; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinFormsApp8 { internal class CommandManage : ICommand { public Dictionary<string, ICommand> Commands = new Dictionary<string, ICommand>(); private Action _action; private Guid _guid; private string _name; Guid ICommand.Guid { get => new Guid(); set => _guid = value; } string ICommand.Name { get => _name; set => _name = value; } public CommandManage(string guid, string name, Action action) { _guid = new Guid(guid); _name = name; _action = action; } public void Execute() { _action(); } public void Add(ICommand imd) { Commands[imd.Guid.ToString()] = imd; } public void Del(ICommand imd) { if (Commands.ContainsKey(imd.Guid.ToString())) Commands.Remove(imd.Guid.ToString()); } } }
private void Form1_Load(object sender, EventArgs e) { CommandManage cmds = new CommandManage("96498A68-F01D-4DCC-B786-BFCB6C250A6A", "root", null); cmds.Add(new Command("96498A68-F01D-4DCC-B786-BFCB6C250A63", "leaf",null)); cmds.Add(new Command("96498A68-F01D-4DCC-B786-BFCB6C250A61", "leaf", null)); var leafq = new CommandManage("96498A68-F01D-4DCC-B786-BFCB6C250A93", "leaf", null); cmds.Add(leafq); leafq.Add(new Command("96498A68-F01D-4DCC-B786-BFCB6C250A65", "leaf", null)); leafq.Add(new Command("96498A68-F01D-4DCC-B786-BFCB6C250A67", "leaf", null)); var mm = cmds; }
标签:guid,name,C#,System,模式,树形,new,using,Guid From: https://www.cnblogs.com/itsone/p/18092610