Below are some screen shots of examples taken from a sample
application that I developed. The first example is querying the "I Luv
Books" provider by ISBN.
Figure 1
When searching for "ASP.NET," the following
results come up.
Figure 2
Switching over to the "Books Express" provider,
below are the two screenshots of using it for connecting to the data store.
Figure 3
Figure 4
At the root of this is a BookAdapter object that represents
one of the two available book adapters. The following code gets the correct
adapter to use based on the radio button list.
Listing 7
private BookAdapter GetAdapter()
{
if (this.rbBooksExpress.Checked)
return new BooksExpressAdapter();
else
return new ILuvBooksAdapter();
}
Note that this could pull the provider name/type from a data
source or configuration file. For this example, I used the Template Method
pattern to retrieve the object. Next, based on which button was clicked, an
event handler runs, passing the book results to another method.
Listing 8
private void btnISBNSearch_Click(object sender, EventArgs e)
{
BookAdapter adapter = this.GetAdapter();
Book book = adapter.RetrieveByISBN(this.mtbISBN.Text);
if (book == null)
this.NotifyNoBooks();
else
this.LoadBookResults(new Book[]
{
book
}
);
}
private void btnSearch_Click(object sender, EventArgs e)
{
BookAdapter adapter = this.GetAdapter();
Book[]books = adapter.RetrieveBySearch(this.txtSearch.Text, chkAny.Checked);
if (books == null || books.Length == 0)
this.NotifyNoBooks();
else
this.LoadBookResults(books);
}
Because we reference the provider through the BookAdapter
abstract class, we do not need to know anything specific about the provider,
which makes this portion of the code dynamic. That is the benefit of
inheritance and polymorphism through the adapter pattern. Derived types do not
need to declare their specific type, so we can work with the class interface
that BookAdapter provides. NotifyNoBooks simply shows a message box and so I
will not show that, but LoadBookResults takes the array and creates a series of
list items for each book.
Listing 9
private void LoadBookResults(Book[]books)
{
this.lvwBooks.Items.Clear();
foreach (Book book in books)
{
ListViewItem item = new ListViewItem(book.Title);
item.SubItems.Add(book.Author);
item.SubItems.Add(book.Description);
item.SubItems.Add(book.ISBN);
this.lvwBooks.Items.Add(item);
}
}