Definition: The Composite pattern composes objects into tree structures to represent part-whole hierarchies.
Usage: Composite lets other code treat individual objects and compositions of objects uniformly.
interface Array {
Object getElementAt(int index)
void setElementAt(Object object, int index)
int size()
}
class MergedArray implements Array {
MergedArray(Array array1, Array array2) {
this.array1 = array1;
this.array2 = array2;
}
Object getElementAt(int index) {
if(index >= array1.size()) {
if(index >= size())
throw an exception
else
return array2.getElementAt(index - array1.size());
}
else
return array1.getElementAt(index);
}
void setElementAt(Object object, int index) {
if(index >= array1.size()) {
if(index >= size())
throw an exception
else
array2.setElementAt(object, index - array1.size());
}
else
array1.setElementAt(object, index);
}
int size() {return array1.size() + array2.size();}
Array array1, array2;
}
In most cases, it would be better just to create a new array containing all the elements. It might make sense to use this class when there will only be a small number of accesses to the new array. It might take longer to allocate new memory than to use the merged array (with its extra overhead). Generally, this class is useless, but other similar classes might not be.
The classical example of a menu that can contain other menus as well as menu items is a much better example, but this catalog uses non-standard examples. If every design pattern catalog used the same examples for every pattern, there might as well only be one design pattern catalog.
Copyright (C) 2008-2009 Steven Fletcher. All rights reserved.