开发者

composite pattern design questions

I have a question about two operations you commonly see in an example Composite class diagram.

* GetDescendents

* GetChild(int)

A common exampl开发者_JAVA百科e being Files and Directories, I'll stick with that. Let's say the operation of interest is Size, so File has a real size and Directory has a Size derived from the recursive iteration of GetDescendents. So far so good. My question has to do with the client's use of GetDescendents. Say you need the files in a directory that are images for some given operation. So in practice, you use some combination of GetDescendents and Children to return the imageFiles (depending on whether the client wanted all nested imageFiles or just at the root level).

So question number one is, wouldn't you likely have a GetImageFiles method on the composite as opposed to making the client figure it out? And assuming so, is GetDescendents ever practical to expose to client callers (like the ImageViewer) outside of the composition?

The second question about GetChild(int); is the int an ordinal position index to return a single child? A level of depth into GetDescendents? What would be an example of how a client would use that method?

Cheers,

Berryl


These questions are not about the composite pattern per se, but about the bigger issue of how you do API design and communicate unambiguously your intent as a class developer.

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

It's up to you as a class designer to expose enough operations as to make your class understandable and usable. If you think that a very common operation would be to get the image files on your directory structure, you could expose a GetAllImageFiles() method. For a more general directory class though, this choice seems arbitrary and it's at the wrong level of abstraction. Why are image files so special? You could, instead, provide a more general method that would get all files based on their extensions or a method that takes a predicate to filter the results based on client provided criteria.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜