We know that some design patterns are found so useful that they become features of the language itself.
For instance, the interface IEnumerator
which is implemented by Array
object.
This helps in separating the iterator from the collection object. The internal representation of the object is encapsulated.
The pattern: Iterator Pattern
I have just come across another interface IStructuralComparable
(msdn). This is used to compare the structure of two collection types using StructuralComparisons
(msdn) class.
The intent of this interface seems to be thus:
My understanding is that it’s used for collection like types, and
encapsulates the structural part of the comparison, but leaves the
comparison of the elements to a comparer passed in by the user.
(link)
(Got from the comments section of the question)
Is this an implementation of any familiar design pattern?
If yes, which pattern is it?
I don’t believe there is a commonly used pattern to describe this. I would think of it as “broken composite pattern”, because it seems to me that they nearly use the composite pattern and if they actually used it then it would work better.
As it was implemented, you compare collections using IStructuralComparable, which requires you to pass in an IComparer to use in comparing individual elements from the two structures. Since IComparer and IStructuralComparable are two different interfaces, you have problems if the elements of the IStructuralComparable are themselves collections, which now get compared with IComparer. But if you prefered IStructuralComparable to IComparer at the top level, why don’t you prefer it now?
If the composite pattern had been used the interior nodes (collections) would have the same interface as the leaf nodes (non-collections) and would handle recursive substructures more cleanly. (I’ve actually implemented structural comparisons exactly this way).
So, to me at least the problem looks like a composite pattern, but the solution looks like “near the composite pattern but really not as good”. This must have been done for historical reasons, since lots the IComparer interface has been implemented many times in and out of the .NET framework, and a composite interface wouldn’t match it.
2
I’d say this would be a strategy pattern.
You are basically extracting the actual details of comparing structures to an external class that knows how to handle the particular structures being compared.
For example, An implementation of IStructureComparable for a list would only need to scan a flat list whereas an implementation for a binary tree would also need to take into account the branching of the tree (e.g. it would perhaps use the depth of the trees as a way to order them.)
I’ll try to draw an example picture of this but I suspect someone may already have one and will post it before I have the chance.
4