The Adapter Pattern Posted on August 26, 2007 @ 20:39 books, csharp, designpatterns
"The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces." - Head First Design Patterns
Head First Design Patterns (Head First) by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra
If you're trying to build a presentation layer that is platform agnostic, you might turn to adapters for simple UI controls. For example in ASP.NET there is a drop down list control, and in Win Forms there is the Combo Box control. A quick an easy adapter to the two controls might look like:
public interface IDropDownListAdapter
{
void BindTo( IEnumerable<IDropDownListItem> pairs );
IDropDownListItem SelectedItem { get; }
}
Each drop down list item might look like:
public interface IDropDownListItem
{
string Text { get; }
string Value { get; }
}
A concrete implementation for a Win Forms application might look like:
public class DesktopDropDownList : IDropDownListAdapter
{
public DesktopDropDownList( ComboBox dropDown )
{
_dropDown = dropDown;
_pairs = new Dictionary<string, IDropDownListItem>( );
}
public void BindTo( IEnumerable< IDropDownListItem > pairs )
{
if ( pairs != null )
{
_pairs = new Dictionary< string, IDropDownListItem >( );
foreach ( IDropDownListItem pair in pairs )
{
_dropDown.Items.Add( pair.Text );
_pairs.Add( pair.Text, pair );
}
_dropDown.SelectedIndex = 0;
}
}
public IDropDownListItem SelectedItem
{
get { return !string.IsNullOrEmpty( _dropDown.Text ) ? _pairs[ _dropDown.Text ] : null; }
}
private ComboBox _dropDown;
private IDictionary< string, IDropDownListItem > _pairs;
}
A concrete implementation for a ASP.NET application might look like:
public class WebDropDownList : IDropDownListAdapter
{
public WebDropDownList( DropDownList dropDown )
{
_dropDown = dropDown;
}
public void BindTo( IEnumerable< IDropDownListItem > pairs )
{
if ( pairs != null )
{
foreach ( IDropDownListItem pair in pairs )
{
_dropDown.Items.Add( new ListItem( pair.Text, pair.Value ) );
}
}
}
public IDropDownListItem SelectedItem
{
get { return new DropDownListItem( _dropDown.SelectedItem.Text, _dropDown.SelectedItem.Value ); }
}
private DropDownList _dropDown;
}
And voila... we can write a presentation layer that binds data to an IDropDownListAdapter, without having to be specific to WinForms, ASP.NET, WPF, Silverlight etc.
public Presenter( IView view )
{
_view = view;
}
public void Initialize( )
{
IList< IDropDownListItem > items = new List< IDropDownListItem >( );
items.Add( new DropDownListItem( "Yes", "1" ) );
items.Add( new DropDownListItem( "No", "2" ) );
_view.AreYouHappy.BindTo( items );
}