Adapter Design Pattern – Object Oriented Design – C Sharp

0
  Uncategorized

The Adapter design pattern in object oriented design enables a system to use classes whose interfaces don’t quite match its requirements. It is especially useful for off-the-shelf code, for toolkits, and for libraries. Many examples of the Adapter pattern involve input/output because that is one domain that is constantly changing. For example, programs written in the 1980s will have very different user interfaces from those written in the 2000s. Being able to adapt those parts of the system to new hardware facilities would be much more cost effective than rewriting them.

adapter-design-pattern-uml-diagram

adapter-design-pattern-uml-diagram

Toolkits also need adapters. Although they are designed for reuse, not all applications will want to use the interfaces that toolkits provide; some might prefer to stick to a well-known, domain-specific interface. In such cases, the adapter can accept calls from the application and transform them into calls on toolkit methods.

Adapter Pattern

Interface ITarget

Class Adapter implements ITarget inherits Adaptee

Class Adaptee

Class Client

Member Variables Member Variables Member Variables Member Variables
ITarget adapter 
Member Functions Member Functions Member Functions Member Functions
Request Request calling base.SpecificRequest SpecificRequest
Use it when
You Have Domain specific interface.Class to connect to mismatched interface
You want
  1. Create reusable class to co-operate with yet to build classes
  2. Change names of method as called and as implemented
  3. Support different set of methods for different purpose

 

Choose which type of adapter you need
  1. Class adapter: Invisible to client
  2. Object adapter: can be sub-classed
  3. Two way adapter: Different clients can view object differently
  4. Pluggable adapter: Adapter can be put in and taken out

C Sharp Implementation of Adapter Design Pattern:

using System;
namespace Adapter.Structural
{
class MainApp
{
static void Main()
{
Target target = new Adapter();
target.Request();
// Wait for user
Console.ReadKey();
}
}
class Target
{
public virtual void Request()
{
Console.WriteLine("Called Target Request()");
}
}
class Adapter : Target
{
private Adaptee adaptee = new Adaptee();
public override void Request()
{
adaptee.SpecificRequest();
}
}
class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()");
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *