What is meant by Composite Design Pattern?
>> Friday, May 27, 2011
COMPOSITE:
Build a complex object out of elemental objects and itself like a tree structure.
Build a complex object out of elemental objects and itself like a tree structure.
Where to use & benefits
- Want to represent a part-whole relationship like tree folder system
- Group components to form larger components, which in turn can be grouped to form still larger components.
- Related patterns include
Example
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;
}
....
}
0 comments:
Post a Comment