Tuesday, October 09, 2007

* Patterns : Composite Structural Pattern

Composite Structural Pattern is applicable when you need to deal with whole-part kind of relationships or tree kind of structures. It helps client to deal with individual or composite objects in a uniform manner and thus abstracts the client from complexities of internal structure.

Consider the following class diagram :

Composite

In the above diagram Book is a simple type but LibrarySection is a complex type and is composed of Book type instances. But both have same base which is BookBase and so both the simple type and composite type have same methods exposed to client.

The client code will look like following :

public class Client
{
    Book cSharpBook,vbBook,historyBook,religion;
    LibrarySection techBooks, nonTechBooks, library;
    public void Run()
    {
        cSharpBook = new Book("CSharp Book");
        vbBook = new Book("Visual Basic Book");
        techBooks = new LibrarySection("Technical Books");
        techBooks.Add(cSharpBook);
        techBooks.Add(vbBook);
        techBooks.List();

        Console.WriteLine("----------------------------------------------------------");

        historyBook = new Book("History Book");
        religion = new Book("Religion Book");
        nonTechBooks = new LibrarySection("Non Technical Books");
        nonTechBooks.Add(historyBook);
        nonTechBooks.Add(religion);
        nonTechBooks.List();

        Console.WriteLine("----------------------------------------------------------");

        library = new LibrarySection("Library");
        library.Add(techBooks);
        library.Add(nonTechBooks);
        library.List();
    }
}

By using this pattern a more complex type could also be created by adding the instances of LibrarySection to the same type.

You can download the complete source code from here : Composite Structural Pattern Source Code

No comments:

Post a Comment