Monday, October 15, 2007

* Patterns : Decorator Structural Pattern

The primary use of 'Decorator Structural Pattern' is to add behaviors to object at runtime. It generally involves wrapping the original object with the decorator object which adds the new behaviors but keep the structure of original object intact. Multiple behaviors can be added out of given options based on decision criteria.

Consider the class diagram below :

Decorator

There is a BookBase class which is extended based on subjects of books and types of books. FictionBook subclasses BookBase based on subject/category while VideoBookBase subclasses BookBase based on type of book.

Now BookBase has a method called DisplayInfo() which is used to display about book. If DisplayInfo is called on FictionBook object it will display only the properties which are common to all display books, but suppose the fiction book is a video book and the DispayInfo should also display the duration, we use the above pattern as below :

The client code looks like following :

public class Client
{
    FictionBook bookFiction;
    VideoBookBase videoBookFiction;
    public void Run()
    {
        bookFiction = new FictionBook();
        //NonFictionBook bookNonFiction = new NonFictionBook();
        videoBookFiction = new VideoBook(bookFiction);
        //VideoBookBase videoBookNonFiction = new VideoBook(bookNonFiction);

        bookFiction.DisplayInfo();
        videoBookFiction.DisplayInfo();
        //videoBookNonFiction.DisplayInfo();
    }
}

FictionBook object is wrapped by VideoBook at runtime.

Download full source code : Decorator Structural Pattern

 

No comments:

Post a Comment