Summer_feeds
Just another WordPress.com weblog

Composite Pattern


Composite Pattern-  A tree structure of simple and composite objects

Is concerned about the Tree structure behavior.

A normal tree consists of  nodes and leafs.

  • Leaf doesnot have a follwing node following it.
  • Node have a following node below it.
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
    C# Implementation of composite Pattern

// Structural Pattern:COMPOSITE
using System;
using System.Collections;
//the single interface for primitives & composite types.|
abstract class Component
{
abstract public void AddChild(Component c);
abstract public void Traverse();
}
//A primitive type.
class Leaf : Component
{
private int value = 0;
public Leaf(int val)
{
value = val;
}
public override void AddChild(Component c)
{
//no action; This method is not necessary for Leaf
}
public override void Traverse()
{
Console.WriteLine(“Leaf:”+value);
}
}
//A composite type.
class Composite : Component
{
private int value = 0;
private ArrayList ComponentList = new ArrayList();
public Composite(int val)
{
value = val;
}
public override void AddChild(Component c)
{
ComponentList.Add(c);
}
public override void Traverse()
{
Console.WriteLine(“Composite:”+value);
foreach (Component c in ComponentList)
{
c.Traverse();
}
}
}
class MyMain
{
public static void Main()
{
//creating a TREE structure.
Composite root = new Composite(100);// Root
Composite com1 = new Composite(200); //Composite 1
Leaf l1 = new Leaf(10);//Leaf1
Leaf l2 = new Leaf(20);//Leaf2
//Add two leafs to composite1
com1.AddChild(l1);
com1.AddChild(l2);
Leaf l3 = new Leaf(30);//Leaf3
root.AddChild(com1);//Add composite1 to root
root.AddChild(l3);//Add Leaf3 directlt to root
root.Traverse();//Single method for both types.
}
}

Advertisements

No Responses to “Composite Pattern”

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: