Definition
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Summary
The gang of four definition is "Convert the interface of a class into another interface clients expect. Adpater lets the classes work together that couldn't otherwise because of incompatible interfaces". Below is an example that uses a third party payment system, this also uses the Factory design pattern.
UML class diagram
Participants
The classes and/or objects participating in this pattern are:
- Target - defines the domain-specific interface that Client uses.
- Adapter - adapts the interface Adaptee to the Target interface.
- Adaptee - defines an existing interface that needs adapting.
- Client - collaborates with objects conforming to the Target interface.
Sample code in C#
///
/// MainApp startup class for Structural
/// Adapter Design Pattern.
///
class MainApp
{
///
/// Entry point into console application.
///
static void Main()
{
// Create adapter and place a request
Target target = new Adapter();
target.Request();
// Wait for user
Console.ReadKey();
}
}
///
/// The 'Target' class
///
public class Target
{
public virtual void Request()
{
Console.WriteLine("Called Target Request()");
}
}
///
/// The 'Adapter' class
///
class Adapter : Target
{
private Adaptee _adaptee = new Adaptee();
public override void Request()
{
// Possibly do some other work
// and then call SpecificRequest
_adaptee.SpecificRequest();
}
}
///
/// The 'Adaptee' class
///
class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()");
}
}
-
-
Leest(708)
-
Permalink