GoF defines Adapter pattern as "Convert the interface of a class into another interface that the clients expect.
Adapter lets classes work together that couldn't otherwise because of incompatible interfaces."
Adapter:
Convert the interface of a class into another interface clients
expect. Adapter lets the
classes work together that couldn't
otherwise because of incompatible interfaces
--> Generally the adapter pattern transforms one interface into another,
--> but it can simply wrap the behavior to isolate your class from the underlying implementation.
--> The adapter pattern is usually used when you don't have control over the target class
--> My primary use of the adapter pattern would be to create wrappers for a framework class that doesn't implement an interface.
-->So now the client can use the same interface to perform operations using both underlying objects.
The Adapter pattern is particularly useful when we have two classes that perform similar functions but have different interfaces.
The client wants to use both classes, so instead of having conditional code scattered all around the client code, it would be better and simpler to understand if these two classes share the same interface. We cannot change the class interfaces, but we can have an Adapter which allows the client to use a common interface to access the underlying classes.
//Just do the operation now
//Library One
//Library One
//Library Two
//Adapter interface for our concrete adapters.
//Adapter interface for our concrete adapters.
//Concrete Adapter classes to user the two libraris
public void Do()
{
static void Main(string[] args)
{
IAdapter adapter = null;
Console.WriteLine("Enter which library you wanna use to do operations{1,2}");
int x = Console.Read();
if (x == 1)
adapter = new AdapterOne();
else if (x == 2)
adapter = new AdapterTwo();
adapter.Do();
}
}
class LibraryOne
{
public void OneLibAction()
{
Console.WriteLine("Using Library One to perform the action");
}
}
class LibraryTwo
{
public string TwoLibAction()
{
return "Using Library Two to perform the action";
}
}
interface IAdapter
{
void Do();
}
class AdapterOne : IAdapter
{
private LibraryOne one = null;
public AdapterOne()
{
one = new LibraryOne();
}
{
one.OneLibAction();
}
}
class AdapterTwo : IAdapter
{
private LibraryTwo two = null;
public AdapterTwo()
{
two = new LibraryTwo();
}
public void Do()
{
Console.WriteLine(two.TwoLibAction());}
}
No comments:
Post a Comment