Junior — Middle
Can you explain the principle of operation and purpose of the Adapter pattern in programming?
sobes.tech AI
Answer from AI
The Adapter pattern is used to "adapt" the interface of one class to the interface expected by the client. This allows incompatible classes to work together.
For example, if you have a class with one interface and want to use a class with a different interface, you create an adapter that implements the required interface and internally calls the methods of the adaptable class.
Example in C#:
// Interface expected by the client
interface ITarget
{
void Request();
}
// Class with an incompatible interface
class Adaptee
{
public void SpecificRequest() {
Console.WriteLine("Calling specific request");
}
}
// Adapter that makes Adaptee compatible with ITarget
class Adapter : ITarget
{
private Adaptee _adaptee = new Adaptee();
public void Request() {
_adaptee.SpecificRequest();
}
}
Thus, the client can work with the object through the ITarget interface without worrying about the fact that internally a class with a different interface is used.