[review]Design Pattern:Composite

Composite

Composite pattern is dedicated to resolve the whole and part issue in application. The whole can be parted into different parts and the parts can be composited into a very whole, to resolve the whole-part issue.

When we use this pattern

if you want to express the whole-part hierarchy circumstance, like the TreeView in ASP.NET WinForm. like the dom in Javascript, the part has the same structure but it maybe belongs to another part(another part's child) . the part also can have the children with the same stucture as itself. 

Every part here we call it as a component. obviously, it is better for users that they just consider everything as a component no matter how the very component is composited, no matter how many children or leaves the component has. Just a componeng from the user's Perspective

Roles in this pattern

  • Component: define the interfaces for the component. implement the default functions and any other function for managing the component .
  • Leaf: the very component but with no children. in ther real world. it is like a leaf
  • Composite: the very component getting all functions of the component. designed for storing the children
  • Client: communicate with the component.
This pattern is easy to understand but hard to say(at least for me). thinking carefully about the TreeView in C# or the real tree can help you get a better understanding for this pattern.
 
A small demo designed for this:
namespace Composite
{
public abstract class Component
{
public abstract void Operation();

public abstract void Add(Component com);

public abstract void Remove(Component com);

}

public class Comosite : Component
{
List<Component> children = new List<Component>();
public override void Operation()
{
//
}

public override void Add(Component com)
{
children.Add(com);
}

public override void Remove(Component com)
{
if (children.Count > 0)
{
children.Remove(com);
}
}
}

public class Leaf : Component
{
public override void Operation()
{
//
}

public override void Add(Component com)
{
throw new InvalidOperationException();//can't implement the add function on leaf
}

public override void Remove(Component com)
{
throw new InvalidOperationException();//can't implement the remove function on leaf
}
}

class Client
{
static void Main(string[] args)
{
Component root = new Comosite();

root.Add(new Leaf());
root.Add(new Leaf());

Component children1 = new Comosite();

Component children2 = new Comosite();

root.Add(children1);
root.Add(children2);

}
}
}
This situation is very often in our real world, ranges from the treeview to the a company's structure hierachy. IMO, to better understand this pattern you got to think more about the real world.

posted on 2011-11-08 22:42 小AI 阅读(24) 评论(0) 编辑 收藏

(评论功能已被博主禁用)

导航