I've seen a lot of posts recently on why Singletons should be avoided. However, I can't see any of those problems with the following solution to a common problem: static inheritance.
For example, I was recently working on a library that scrapes the HTML source of a website and parses its contents into objects. The problem here is, the site has different types of content- articles, videos, etc. In my initial code, I had several different static 'supplier' classes- i.e. ArticleSupplier
- that I quickly found shared a lot of boilerplate code (i.e. argument checks).
I could have made the classes instance-based, but it seems pointless: new ArticleSupplier()
has no state; all its methods depend on the arguments passed to them. Instantiating another one is just a waste of memory.
This has brought me to thinking about using the Singleton pattern: a base class could perform boilerplate code checks and then call the derived class' implementation; the derived class could then control access with a singleton. Here's a simple example in C#:
abstract class Supplier
{
IEnumerable<IModel> RecentModels(int amount)
{
return ModelsBefore(DateTime.Now, amount);
}
IEnumerable<IModel> ModelsBefore(DateTime date, int amount)
{
CheckDate(date);
CheckAmount(amount);
return InternalBefore(date, amount);
}
abstract IEnumerable<IModel> InternalBefore(DateTime date, int amount);
}
class ArticleSupplier
{
private static readonly ArticleSupplier _Instance = new ArticleSupplier();
private ArticleSupplier() { }
public static ArticleSupplier Instance { get { return _Instance; } }
override IEnumerable<IModel> InternalBefore(DateTime date, int amount)
{
// implementation
}
}
Now, you can focus on the implementation within ArticleSupplier
without writing the same boilerplate code, and at the same time control instantiation of the object. I'd like to emphasize again that this is completely thread-safe because the singleton has no state, which is why the method was static in the first place.
Is this an appropriate use of the Singleton pattern, or are there still some pitfalls that I'm missing?
ArticleSupplier _Instance
a Singleton because it's static? Anyway, this is just ordinary composition, not inheritance.Instance
property should be static. Fixed.switch (type)
code, like in here.