1 Adapter
Definition:-
1 Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
2 Wrap an existing class with a new interface.
3 Match interfaces of different classes
4 Adapt an interface to an expected interface
5 Impedance match an old component to a new system
6 Adapter is about creating an intermediary abstraction that translates, or maps, the old component to the new system. Clients call methods on the Adapter object which redirects them into calls to the legacy component. This strategy can be implemented either with inheritance or with aggregation
Core component:-
- Client. The client class is that which requires the use of an incompatible type. It expects to interact with a type that implements the ITarget interface. However, the class that we wish it to use is the incompatible Adaptee.
- ITarget. This is the expected interface for the client class. Although shown in the diagram as an interface, it may be a class that the adapter inherits. If a class is used, the adapter must override its members.
- Adaptee. This class contains the functionality that is required by the client. However, its interface is not compatible with that which is expected.
- Adapter. This class provides the link between the incompatible Client and Adaptee classes. The adapter implements the ITarget interface and contains a private instance of the Adaptee class. When the client executes MethodA on the ITarget interface, MethodA in the adapter translates this request to a call to MethodB on the internal Adaptee instance.
Example :-
public class Client 
{private ITarget _target;
public Client(ITarget target){_target = target;}
public void MakeRequest(){_target.MethodA();}}
public interface ITarget{void MethodA();}
public class Adaptee{public void MethodB(){Console.WriteLine("MethodB called");}}
public class Adapter : ITarget{Adaptee _adaptee = new Adaptee();
public void MethodA(){_adaptee.MethodB();}}
Check list:-- Identify the players: the component(s) that want to be accommodated (i.e. the client), and the component that needs to adapt (i.e. the adaptee).
- Identify the interface that the client requires.
- Design a “wrapper” class that can “impedance match” the adaptee to the client.
- The adapter/wrapper class “has a” instance of the adaptee class.
- The adapter/wrapper class “maps” the client interface to the adaptee interface.
- The client uses (is coupled to) the new interface
- Identify the players: the component(s) that want to be accommodated (i.e. the client), and the component that needs to adapt (i.e. the adaptee).