sabato 27 aprile 2019

Design Patterns: Composite Patter

Composite patter essentially implements a tree of objects and you can use it everytime you need a tree data structure.
At first you define a class for a node with private information for the node and the list of child node. In the constructor you pass the information to create the node, also you need a method to add a child node that add the child node in the private list of child nodes and also a method to get all the child nodes. You also need an class for the root node to create the tree. the root node class has a private node that is the root node. you need a method to get this root node, then you call rootnode.add to add child nodes to root node and build the tree. A classic use of composite pattern is associated to the filesystem that is a tree data structure.

public class Node
{
      private NodeInfo nodeInfo;
      private List<Node> childNodes;
      public void Node(NodeInfo info)
     {
           nodeInfo = info;
           childNodes = new List<Node>();
     }

     public NodeInfo GetInfo()
    {
           return nodeInfo;
    }

     public void Add(Node node)
     {
            childNodes.Add(node);
     }

     public IEnumerable<Node> GetChildNodes()
    {
            foreach(var node in childNodes)
                   yield return node;
    }

}

pubic class Root
{
      private Node root;

      public Root(Node node)
      {
             root = node;
      }

      public Node getRoot()
      {
             return root;
      }
}

Usage:
var rootNode = new Node(nodeInfo);
var firstChild = new Node(nodeInfo1);
var secondChild = new Node(nodeInfo2);
var tree = new Root(rootNode);
var node = tree.getRoot(),
node.Add(firstChild);
node.Add(secondChild);
foreach(n in node.GetChildNodes())
     Console.WriteNode(n);

Nessun commento:

Posta un commento