Composite
{
public string name;
abstract public void display();
}
public class FileBasic : elementBasic
{
public FileBasic(string h)
{
name = h;
}
public override void display()
{
MessageBox.Show("F: " + name ) ;
}
}
public class DirBasic : elementBasic
{
ArrayList files = new ArrayList();
public DirBasic(string h)
{
name = h;
}
public void add( elementBasic h)
{
files.Add(h);
}
public override void display()
{
MessageBox.Show("D: " + name ) ;
foreach(elementBasic i in files)
{
i.display();
}
}
}
and two derived classes are filebasic and dirBasic.
Notice that DirBasic can accommodate children Add method.
Conceptually this is a tree of filestructure. what does a tree need? ---a kind of node that can take nodes/leaves.
Notice the flavor we are giving to dirbasic to distinguish from filebasic, inspite of accommodating directories/files in directory.
Imagine I want to accommodate a new entity called "shortcutFiles"
I can simply do
public class ShortcutFileBasic : elementBasic
{
FileBasic mytarget; // these are reference type objects
public ShortcutFileBasic (FileBasic h)
{
name = "shortcut to " + h.Name;
mytarget = h;
}
public override void display()
{
MessageBox.Show("F: " + name ) ;
}
}
I can similarly add shortcut to directories. (be prepared for design scalability)
http://www.dofactory.com/Patterns/PatternComposite.aspx defines the pattern as
--Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Try to use this pattern to achive
1) a binary tree
2) Imagine a society where man and woman have many-to-many relation. And woman can have children(that are male or female).
We can think of a design with human , Male and Female classes.
Notice the flexibility the pattern give.
We can accomodate objects that have a heirarchy and also we can ensure the connections under business rules.
Rules like
files cannot have directories
Directories can have files
Directories can have directories too.
'shortcut files' point to files
'shortcut dirs' point to files etc.....
where can i use this?
where ever a tree like structure is there. and you have typical busineess rules.
I prefer using this in a long living objects like
Application/session objects on web
Or Menuitems in a windows application.
We have different objects in a game application.
We have balls and boxes. which can be blue/red/yellow. Rules are
1) Blue ball can contain only red boxes.
2) Any box can contain blue or yellow ball or any box.
3) Yellow balls cannot contain any balls.
Create the class structure.