Datasheet

12
x
CHAPTER 1 PRIMER
THE DELEGATE STRATEGY
The whole interface-based Strategy approach can be eliminated in favor of a well-de ned delegate
type and an instance of an anonymous method:
delegate bool SearchProc<T>(T candidate);
class Database<T> where T : class
{
private List<T> data = new List<T>();
public Database() { }
public void Add(T i) { data.Add(i); }
public T Find(SearchProc<T> algorithm)
{
foreach (T i in data)
{
if (algorithm(i))
return i;
}
return null;
}
}
The real savings comes at the point where the student login code does the lookup; because the
search now takes a delegate instance, the criteria by which the
Student is looked up can be as rich
or as simple as the case demands:
Student s = null;
while (s == null)
{
Console.Write(“Please enter your first name:”);
string first = Console.ReadLine();
Console.Write(“\nPlease enter your last name:”);
string last = Console.ReadLine();
s = Students.Find(delegate (Student c) {
return
c.FirstName == first &&
c.LastName == last
});
if (s == null)
Console.WriteLine(“Sorry! Couldn’t find you”);
}
// Do something with s
Now, all kinds of performance optimization can be done in the Database<T> class, because the cli-
ent code remains ignorant of how the search is done. Instead, it simply speci es what to match (or if
you will, how the match is done, instead of how the search is done).
However, the
Database isn’t done yet: if the Database is later going to fi nd all Instructors that
teach a particular subject, it needs the capability to return more than one object if the criteria is
matched:
class Database<T> where T : class
{
c01.indd 12c01.indd 12 10/1/2010 3:20:37 PM10/1/2010 3:20:37 PM