Monday, 18 April 2016

Composite pattern : Example 1



A component has many elements and itself which has many elements and itself, etc.
A file system is a typical example.

Directory is a composite pattern.
When you deal with Directory object, if isFile() returns true, work on file, if isDirectory() returns true, work on Directory object.

class Directory {
   Directory dir;
   File[] f;
   ...
   boolean isDirectory() {
       return f == null;
   }
   boolean isFile() {
       return f != null;
   }
   File getFile(int i) {
      if (isFile())
         return f [i];
      return null;
   }
   Directory getDirectory() {
      if (isDirectory())
          return dir;
      return null;
   }
   ....
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.