Composite Pattern

  • Structural pattern
  • The intent of this pattern is to compose objects into tree structures to represent part-whole hierarchies. As such it lets client treat individual objects and compositions of object uniformly : as if they all were individual objects.
    • XML document structure
    • Composing a drawing
  • Composite:- Stores child components and defines behavior for components having children.
  • Leaf :- Leaf represents leaf objects in the composition, and has no children. It defines behavior for primitive objects in the composition.
  • Client:- Manipulates objects in the compositions through the component interface.
  • Makes the client simple¬†
  • Easy to add new kinds of components – OC principle is maintained
  • It can make the overall system too generic – disadvantage
  • Related Patterns :- Chain of Responsibility, Iterator pattern, Visitor pattern
				
					namespace compositepattern
{
    public abstract class FileSystemItem
    {
        public string Name { get; set; }
        public abstract long GetSize();

        public FileSystemItem(string name)
        {
            Name = name;   
        }
    }

    public class File : FileSystemItem
    {
        private readonly long _size;

        public File(string name,long size):base(name)
        {
            _size = size;
        }

        public override long GetSize()
        {
            return _size;
        }
    }


    public class Folder : FileSystemItem
    {
        private List<FileSystemItem> _fileSystemItem { get; set; } = new();

      
        public Folder(string name):base(name)
        {
        }

        public void Add(FileSystemItem itemToAdd)
        {
            _fileSystemItem.Add(itemToAdd);
        }

        public void Remove(FileSystemItem itemToAdd)
        {
            _fileSystemItem.Remove(itemToAdd);
        }

        public override long GetSize()
        {
            var totalsize = 0L;
            _fileSystemItem.ForEach(fileItem => {
                totalsize += fileItem.GetSize();
            });
            return totalsize;
        }
    }
}

				
			
				
					// See https://aka.ms/new-console-template for more information



using compositepattern;

var rootFolder = new compositepattern.Folder("RootFolder");
var rootFile = new compositepattern.File("rootfile", 100);
var folder1= new compositepattern.Folder("folder1");
var folder2= new compositepattern.Folder("folder2");

rootFolder.Add(rootFile);
rootFolder.Add(folder1);
rootFolder.Add(folder2);

var folder1file1 = new compositepattern.File("folder1file1", 300);
var folder1file2 = new compositepattern.File("folder1file2", 300);
var folder2file = new compositepattern.File("folder2file", 500);
folder1.Add(folder1file1);
folder1.Add(folder1file2);
folder2.Add(folder2file);

Console.WriteLine(rootFolder.GetSize());
Console.WriteLine(folder1.GetSize());
Console.WriteLine(folder2.GetSize());
				
			

1200

600

500

Leave a Comment