I think Composite pattern still applies here. Yes you are correct in saying
that apples are not oranges, and oranges/apples are not folders, but they
may have same ancestor. An analogy would be like
humans, dogs and mice, even though they are different they still are
mammals.
So following Composite pattern, your Orange and Apple objects would descend
from Leaf, whereas Folder object would descend from Composite object. You
could modify the Composite pattern in a way that you would remove Add/Remove
methods from the Component object and introduce them on Composite object, so
only Folder objects would have these methods. Then you could add an enum
property on Folder object which would tell you what type of objects the
Folder contains. Something like (following Composite pattern) :
public enum ObjectType
{
otOrange,
otApple,
otFolder
}
public abstract class MyComponent
{
private ObjectType myType;
public MyComponent()
{
}
protected void SetType(ObjectType aType)
{
myType = aType;
}
public ObjectType MyType
{
get { return myType; }
}
}
public abstract class Composite : MyComponent
{
public abstract void AddChild(MyComponent aChild);
public abstract void RemoveChild(MyComponent aChild);
public abstract MyComponent GetChild(int index);
}
public abstract class Leaf : MyComponent
{
...
}
public class Orange : Leaf
{
public Orange()
{
SetType(otOrange);
}
...
}
public class Apple : Leaf
{
public Orange()
{
SetType(otLeaf);
}
...
}
public class Folder : Composite
{
private ObjectType mContainsType;
public Folder (ObjectType aType)
{
SetType(otFolder);
mContainsType = aType;
}
public override void AddChild(MyComponent aChild)
{
if(aChild.MyType == mContainsType)
// add it to the collection
else
// throw an excpetion since the type is different
}
public abstract void RemoveChild(MyComponent aChild)
{
...
}
public abstract MyComponent GetChild(int index)
{
...
}
}
Hope this helps
Fitim Skenderi
"Dave Veeneman" <da****@nospam.com> wrote in message
news:Of**************@TK2MSFTNGP09.phx.gbl...
I'm puzzling over the best design for a Folder object.
I have two basic domain objects; leat's call them an Apple and an Orange.
The objects are maintained in separate hierarchies, and each hierarchy is
organized by Folder objects. A Folder object can contain either Apples, or
Oranges, or other Folders. A Folder contains only one type of object. For
example, a Folder won't contain Apples and other Folders, or Apples and
Oranges.
What's the best design for the Folder object? I was going to use a GoF
Composite pattern, but it doesn't really seem to fit, since a Folder is
neither an Apple nor an Orange. At this point, I'm leaning toward an
abstract Folder, from which I derive an AppleFolder and an OrangeFolder.
But I'm still puzzling over how clients tell whether a Folder contains other
Folders or fruit objects.
Any advice would be greatly appreciated. Thanks in advance.
--
Dave Veeneman
Chicago