Collections like Array, List, etc which are groupings of objects.
Composites are used in hierarchies to give the same behavior to the composites class as to the leaf/node class. The example from the GoF has both the leaf and composite classes using a common base class or interface.
Many objects in systems I’ve worked with have objects grouped in hierarchies. For a Merchandise hierarchy Items are in Categories, Categories are in Departments, Departments are in Companies. For a Location hierarchy Stores/Warehouses are in Regions, Regions are in Divisions, Divisions are in Companies. For a Calendar hierarchy Days are in Weeks. Weeks are in Periods, Periods are in Years. Categories, Departments, Divisions, Weeks, Years and Companies are all composites.
I can also make an array of Items or Stores or Days. Using that array I can iterate through every objects in the array and call a method/function on each object. But why iterate through the array of objects? Why can’t I just treat the array as a composite which has the same methods/functions as the objects in the array. Instead of iterating through the array I just call the method/function on the array directly and let the array do the heavy lifting of calling that method/function on each object in the array.
I also want to use the array as a duck type of the objects in the array. Assume a function expects an object of type Item. Add some Item objects to a new Array. As an Array of Items is also an Item that Array can also be passed to the function. The Array of Items is dynamically typed. The Array of Items isn’t a composite of Item until you place an Item into the Array at run time.
If a method/function returns a value there could be some way to handle the values returned by every object in the Array. You could just ignore the returned values and return nothing from the Array method/function. Or you could assign some summary operation similar to the summary operations in SQL – Minimum, Maximum, Summation or Average. Or you could assign some arbitrary summary function that accepts a series of returned values and returns a single value.
Is there any language out there that supports this dynamic typing of an Array to the class in the array?