Let's suppose I have a widget class:
struct Widget {
public Color Color { get; set; }
public int Frobbles { get; set; }
}
Now, I need to make a factory to create these widgets, so I build a WidgetFactory:
abstract class WidgetFactory {
public virtual Widget GetWidget();
}
As it turns out, you can make widgets out of several different materials, but the resulting widgets are pretty much the same. So, I have a few implementations of WidgetFactory:
class GoldWidgetFactory : WidgetFactory {
public GoldWidgetFactory(GoldMine goldmine) {
//...
}
public Widget GetWidget() {
Gold g = goldmine.getGold();
//...
}
}
class XMLWidgetFactory : WidgetFactory {
public XMLWidgetFactory(XmlDocument xmlsource) {
//...
}
public Widget GetWidget() {
XmlNode node = //whatever
//...
}
}
class MagicWidgetFactory : WidgetFactory {
public Widget GetWidget() {
//creates widget from nothing
}
}
My question is this: Should WidgetFactory be an abstract class, or an interface? I can see arguments in both directions:
Base class:
- The implementations ARE WidgetFactories
- They might be able to share functionality, (say, a
List<Widget> WidgetFactory.GetAllWidgets()
method)
Interface:
- The implementations do not inherit any data or functionality from the parent
- Their internal workings are completely different
- Only one method is defined
To those answering, this does not (currently) parallel to any real-world problem, but if/when I need to implement this pattern, it would be good to know. Also, "it doesn't matter" is a valid answer.
Edit: I should point out why go through this in the first place. The hypothetical usage of this class hierarchy would be something like:
//create a widget factory
WidgetFactory factory = new GoldWidgetFactory(myGoldMine);
//get a widget for our own nefarious purposes
Widget widget = factory.GetWidget();
//this method needs a few widgets
ConsumeWidgets(factory);
So, having a GetGoldWidget()
method in WidgetFactory is not a very good idea. Plus, perhaps advents in Widget technology allow us to add different and more exotic types of widgets in the future? It's easier and cleaner to add a new class to handle them than shoehorn a method into an existing class.