I am trying to improve my skills with design patterns, so please be easy on me :) In my work I often have to deal with problems where the algorithm is defined, but data structures it is working on are different.
Let's say I have a Counter class, whose responsibility is to simply count items if they match certain criteria (a big simplification). These items may have different structure, so for example:
- if the Counter is running for "text" items, I only count an item if its length is greater than X
- if the Counter is running for "image" items, I only count an item if it's a JPEG image.
It feels right (for me) to have an AbstractItem class which the counter would work on, but then it also needs associated AbstractCriteria, since criteria are evaluated in different way for each type of item.
Some sort of pseudo code:
class Counter
{
AbstractItemFactory factory; // initialized in constructor
AbstractCriteria criteria; // initialized in constructor
DataProvider provider; // initialized in constructor
int count()
{
int result;
while((Data data = provider.get()) != null)
{
AbstractItem item = factory.create(data);
if(criteria.match(item))
{
result++;
}
}
return result;
}
}
The problem here is that of course AbstractCriteria would not know how to handle AbstractItem. I know it's possible to solve this by using base-to-derived cast inside overriden match() method, but that's not a very good design. It is also possible to use templates, but this will make the code more complicated, so I want to know first if there is any design pattern I could use to achieve what I want. Or maybe my approach to this problem is completely wrong, and there is some easy solution which I just fail to see?
Thanks!
Aucun commentaire:
Enregistrer un commentaire