Thursday, September 3, 2009

Patterns - 018: Collectional patterns ( composite )


Every component or object can be classified into one of the two categories — Individual Components or Composite Components — which are composed of individual components or other composite components. The Composite pattern is useful in designing a common interface for both individual and composite components so that client programs can view both the individual components and groups of components uniformly. In other words, the Composite design pattern allows a client object to treat both single components and collections of components in an identical manner.

This can also be explained in terms of a tree structure. The Composite pattern allows uniform reference to both Nonterminal nodes (which represent collections of components or composites) and terminal nodes (which represent individual components).


Example





The default implementation of these methods consists of what is applicable to FileComponent objects. FileComponent objects are individual objects and do not contain other FileSystemComponent objects within. Hence, the default implementation does nothing and simply throws a custom CompositeException exception. The derived composite DirComponent class overrides these methods to provide custom implementation.




             public abstract class FileSystemComponent {
                 String name;

                 public FileSystemComponent(String cName) {
                     name = cName;
                 }

                 public void addComponent(FileSystemComponent component)
                         throws CompositeException {
                     throw new CompositeException(
                             "Invalid Operation. Not Supported");
                 }

                 public FileSystemComponent getComponent(int componentNum)
                         throws CompositeException {
                     throw new CompositeException(
                             "Invalid Operation. Not Supported");
                 }

                 public abstract long getComponentSize();
             }
         


No comments:

Post a Comment