The essential players in the Composite pattern UML diagram are:
IComponent : Defines the operations for objects in the composition, and any default behavior
that will be applicable across objects of both types
Operation : Performs an operation on IComponent-conforming objects.
Component : Implements IComponent .
Composite : Implements IComponent and containing a list of components.
The client deals only with the IComponent interface, which simplifies its task.
And this the implementation :
using System;
using System.Collections.Generic;
using System.Text; // for StringBuilder
using System.Collections.Generic;
namespace CompositePattern
{
// The Interface
public interface IComponent
{
void Add(IComponent
IComponent
string Display(int depth);
IComponent
T Name { get; set; }
}
// The Component
public class Component
{
public T Name { get; set; }
public Component(T name)
{
Name = name;
}
public void Add(IComponent
{
Console.WriteLine("Cannot add to an item");
}
public IComponent
{
Console.WriteLine("Cannot remove directly");
return this;
}
public string Display(int depth)
{
return new String('-', depth) + Name + "\n";
}
public IComponent
{
if (s.Equals(Name))
return this;
else
return null;
}
}
// The Composite
public class Composite
{
List
public T Name { get; set; }
public Composite(T name)
{
Name = name;
list = new List
}
public void Add(IComponent
{
list.Add(c);
}
IComponent
// Finds the item from a particular point in the structure
// and returns the composite from which it was removed
// If not found, return the point as given
public IComponent
{
holder = this;
IComponent
if (holder != null)
{
(holder as Composite
return holder;
}
else
return this;
}
// Recursively looks for an item
// Returns its reference or else null
public IComponent
{
holder = this;
if (Name.Equals(s)) return this;
IComponent
foreach (IComponent
{
found = c.Find(s);
if (found != null)
break;
}
return found;
}
// Displays items in a format indicating their level in the composite structure
public string Display(int depth)
{
StringBuilder s = new StringBuilder(new String('-', depth));
s.Append("Set " + Name + " length :" + list.Count + "\n");
foreach (IComponent
{
s.Append(component.Display(depth + 2));
}
return s.ToString();
}
}
class CompositeApp
{
static void Main()
{
IComponent
string parameter = "photo";
album.Add(new Component
album = album.Find(parameter);
Console.WriteLine(album.Display(0));
album = album.Remove(parameter);
Console.ReadLine();
}
}
}
Best regards
No comments:
Post a Comment