Datasheet
10
x
CHAPTER 1 PRIMER
return null;
}
}
which works, for now. Unfortunately, although this solves the immediate problem, what happens
when the
Database needs to search for a Student by major, or an Instructor by fi eld? Because
those are properties not specifi ed on the
Person type, once again the Database class will fail.
What’s actually needed here is the ability to search via some completely arbitrary criteria, specifi ed
at the time the search is to happen — if this search were being done in SQL, the programmer could
pass in a
WHERE clause, a search predicate, by which the database could evaluate all the potential
matches and return only those that met the criteria.
This sounds like a pretty good idea and one to which object-orientation has an answer: the Strategy
pattern.
STRATEGY
In design patterns parlance, a Strategy is a setup where an object that implements an algorithm can
be passed in for execution without the client knowing the actual details of the algorithm. More
important, an appropriate Strategy can be selected at runtime, rather than being decided (some
might say hard-coded) at compile-time. This is almost spot-on to what’s needed here, except in this
case the “algorithm” being varied is the criteria by which each potential match is evaluated.
In the classic Strategy implementation, an interface defi nes the parameters and result type to the
algorithm:
interface ISearchCriteria<T>
{
bool Match(T candidate);
}
This, then, enables the Database to be written to be entirely ignorant of the criteria by which
to search:
class Database<T> where T : class
{
private List<T> data = new List<T>();
public T Find(ISearchCriteria<T> algorithm)
{
foreach (T i in data)
{
if (algorithm.Match(i))
return i;
}
return null;
}
}
c01.indd 10c01.indd 10 10/1/2010 3:20:37 PM10/1/2010 3:20:37 PM