What is the need for Composite Pattern in C#?

In Object Oriented Programming and UML, you might be familiar with the composition relationship which is used to establish whole-part relationship. This composition relationship can be achieved in C# application by implementing Composite Pattern.



In composite pattern, objects will be arranged in tree structure wherein each object in the tree structure can be an individual object or a composite object by itself. Composite object means that the object has one or more children.

Composite Pattern ensures that both individual objects and composite objects are treated in the same way and the User will not be aware if he is accessing an individual object or composite object. Here is a sample snippet showing how a tree structure can be created:

class testClass {
public static void Main() {
compositeClass rootNode = new compositeClass(“RootNode”);
rootNode.AddNode(new primitiveClass(“NodeA”));
primitiveClass obj = new primitiveClass(“NodeB”));
rootNode.AddNode(obj);
rootNode.RemoveNode(obj);
rootNode.DisplayTreeStructure();
}
}

In the above example, compositeClass is a class using which the tree structure can be constructed. This class includes several methods namely AddNode to add an object to the current node, RemoveNode to remove the specific object from the current node, DisplayTreeStructure method to display all the objects/nodes that exist in the tree structure. The objects that get added to the tree belong to a class named primitiveClass.

| What is the need for Bridge Pattern in C#? | What is the need for Builder Pattern in C#? | What is the need for Chain of Responsibility Pattern in C#? | What is the need for Command Pattern in C#? | What is the need for Composite Pattern in C#? | What is the need for Decorator Pattern in C#? | What is the need for Flyweight Pattern in C#? | What is the need for Interpreter Pattern in C#? | What is the need for Iterator Pattern in C#? | What is the need for Mediator Pattern in C#? | What is the need for Memento Pattern in C#? | What is the need for Prototype Pattern in C#? | What is the need for State Pattern in C#? | What is the need for Strategy Pattern in C#? | What is the need for Template Method Pattern in C#? | What is the need for unsafe code in C#? | What is the purpose of assert() in C#? | What is the purpose of AutoResetEvent in .NET? | What is the purpose of Console.ReadLine() in C#? | What is the purpose of machine.config file in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.