I have a utility class library I am writing. A have written a factory class that is generic enough that with a few delegates passed in from the caller it can be reused in many different situations. However, one of my colleagues suggested that I use an abstract class or an interface so it is more explicit what functions needed to be overridden. In the model I have created to use the library you would then need to override 2 classes instead of just one. What criteria determines when it is appropriate to use delegate functions or interfaces.
Using a delegate pattern.
Class A
{
Func<string , ReultClass> fun1 {get;set;}
FactoryObj CreateObj()
{
return fun1("")
}
}
Using an interface pattern
Class B
{
InterfaceObj{get;set;}
FactoryObj CreateObj()
{
return InterfaceObj.fun1("")
}
}
If the design is such that the class depends on another class (even a simple class), I would recommend the interface approach, since the object does have to depend on outside code:
In this case, you can still use delegates; I usually write my “anonymous” classes (as Microsoft calls them) with explicit interface implementations, so the name of the delegate property is the same as the name of the interface method it implements:
If there are generics involved (e.g.,
IA<ResultClass>and the correspondingAnonymousA<ResultClass>), then it’s useful to define a factory class, just to clean up the creation syntax: