组合模式(Composite Pattern)
组合模式(Composite Pattern)可以清楚地定义分层次的复杂对象,表示对象的全部或部分层次,使得增加新部件也更容易,它让客户忽略了层次的不同性,而它的结构又是动态的,提供了对象管理的灵活接口。组合模式对于树结构的控制有着神奇的功效,用户对单个对象和组合对象的使用具有一致性。组合模式解耦了客户程序与复杂元素内部结构,从而使客户程序可以像处理简单元素一样来处理复杂元素。也是一种结构型模式。
using System; using System.Text; using System.Collections.Generic; namespace ConsoleApplication { //一般每个接口或类都写在单独的.cs文件中 //本示例为了执行查看方便才写在一起 public abstract class FileObject { public string Name; public List<FileObject> filelist = new List<FileObject>();//组合 public FileObject(string name) { this.Name = name; } //打印文件名 public abstract void PrintName(); public virtual void Add(FileObject fileobject) { Console.WriteLine("Add方法未重写"); } public virtual void Remove(FileObject fileobject) { Console.WriteLine("Add方法未重写"); } } public class txtFile:FileObject { public txtFile(string name) : base(name) { } public override void PrintName() { Console.WriteLine("文件名:" + base.Name); } } public class docFile:FileObject { public docFile(string name):base(name) { } public override void PrintName() { Console.WriteLine("文件名:" + base.Name); } } public class Folder:FileObject { public Folder(string name):base(name) { } public override void Add(FileObject fileobject) { filelist.Add(fileobject); Console.WriteLine(base.Name + "中添加了" + fileobject.Name); } public override void Remove(FileObject fileobject) { if (filelist.Remove(fileobject)) { Console.WriteLine(base.Name + "中删除了" + fileobject.Name); } else { Console.WriteLine("删除失败!"); } } public override void PrintName() { Console.WriteLine("文件名:" + base.Name); } } class Program { static void Main(string[] args) { FileObject txt1 = new txtFile("txt1"); FileObject txt2 = new txtFile("txt2"); FileObject doc1 = new docFile("doc1"); FileObject doc2 = new docFile("doc2"); FileObject folder1 = new Folder("folder1"); FileObject folder2 = new Folder("folder2"); txt1.Add(txt2); doc1.Add(doc2); txt1.Remove(doc1); folder1.Add(txt1); folder1.Add(doc2); folder2.Add(folder1); folder2.Add(doc1); folder1.Remove(txt1); //打印folder1目录下的文件 Console.WriteLine("-------------"); foreach (FileObject file in folder1.filelist) { Console.WriteLine(file.Name); } //打印folder2目录下的文件 Console.WriteLine("-------------"); foreach (FileObject file in folder2.filelist) { Console.WriteLine(file.Name); } Console.ReadKey(); } } }