Challenging Design Templates

I have a question about the two operations that you usually see in the Composite class diagram example.
* GetDescendents
* GetChild (int)

A common example is files and directories, I will stick to this. Assume Size is of interest, so File is the actual size, and Directory is the size obtained from the recursive iteration of GetDescendents. So far, so good. My question is about how customers use GetDescendents. Suppose you need files in a directory that are images for a specific operation. Therefore, in practice, you use some combination of GetDescendents and Children to return imageFiles (depending on whether the client needs all the attached image files or only at the root level).

So, question number one: will you probably not have the GetImageFiles method on the composite, and not so that the client understands it? And is it supposing that GetDescendents are ever practical to expose callers (like ImageViewer) outside of composition?

The second question is about GetChild (int); int int position index to return one child? Depth level in GetDescendents? What will be an example of how the client will use this method?

Cheers
Berryl

+6
design-patterns composite
source share
1 answer

These questions are not about the overall template as such, but about the more important issue of how you are developing the API, and they explicitly communicate their intentions as a class developer.

For example, if you want your GetChild(int) give an indexed immediate child, you can call it GetChildAtIndex(int index) ; if you want the children to be at a certain level in the hierarchy, you could call it GetChildrenAtLevel(int level) (note that this is a plural and returns a collection).

This is for you as a class constructor to expose enough operations to make your class understandable and useful. If you think that a very simple operation is to get the image files in the directory structure, you can open the GetAllImageFiles() method. However, for a more general class of directories, this choice seems arbitrary, and it is at the wrong level of abstraction. Why are image files so special? Instead, you can provide a more general method that will retrieve all files based on their extensions, or a method that uses a predicate to filter results based on criteria provided by the client.

+4
source share

All Articles