I am considering using the Delegate Pattern to get some data necessary for an operation. There are a few different pieces of data that the algorithm needs to run, but they all have default values that can be used if they aren't explicitly set.
If I were to use the delegate pattern, I would define an interface that defines a function for each piece of information that the algorithm would then use to retrieve the data as it needs to.
The other option I see is to have setters on the algorithm object so that those properties can be set explicitly instead of waiting for it to be requested through the delegate pattern.
There are many advantages to using the delegate pattern, but I feel that many of them don't really apply to my situation. One of the biggest things is that it eliminates the need to make specialized subclasses of the object, but in my case, using setters also removes this need.
Also, the delegate pattern allows reuse of delegates like "configurations." If I use setters, everything will have to be explicitly set whenever reconfiguring (instead of just changing delegates around).
I would definitely lean towards using the delegate pattern, my only issue is that this is a public interface that will be used by people who aren't necessarily familiar with the pattern. I feel that using setters would be a more natural way for someone to do it without knowledge of design patterns.
A very simple example of what I am trying to do would be the following:
I have an algorithm that is going to determine if a certain range of characters exits in a string. The configurable options of the algorithm are:
- First character (e.g. "k" )
- Last Character (e.g. "p" will make it search for k,l,m,n,o and p )
- number of characters out of range that need to match
So If I have the string "stack overflow" searching with a character range of "k-p" requiring that at least 4 characters match, it should return true because it contains "k","o","l", and "o".
Using the delegate pattern it would look this this (not necessarily the most efficient):
char startRange = delegate.startChar();
char endRange = delegate.endChar();
int targetCount = delegate.charCount();
int currentCount = 0;
for( char c in targetString )
{
if( c >= startRange && c <= endRange )
{
currentCount++;
if( currentCount == targetCount )
return true;
}
}
return false;
Otherwise the algorithm would require that member functions and variables are defined to set and store those values. The algorithm would look like this.
int currentCount = 0;
for( char c in targetString )
{
if( c >= mStartRange && c <= mEndRange )
{
currentCount++;
if( currentCount == mTargetCount )
return true;
}
}
return false;
The variables may or may not be changed often, and there will definitely be reuse of those variable configurations.
Are there any advantages of the delegate pattern that I am missing? Are there any disadvantages of using setters that I am missing? Any other comments or suggestions?
Thanks!!