Adapter Pattern
Summary: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Sample Code
Code
public class CanonAPI
{
public void TakePhoto() => System.Console.WriteLine("Taking a photo via Canon API.");
}
public class NikonAPI
{
public void PhotoShoot() => System.Console.WriteLine("Taking a photo via Nikon API.");
}
public interface ICameraAPIAdapter
{
void Shoot();
}
public class CanonAdapter : ICameraAPIAdapter
{
public CanonAPI CanonAPI { get; set;}
public CanonAdapter(CanonAPI canonAPI)
{
this.CanonAPI = canonAPI;
}
public void Shoot()
{
this.CanonAPI.TakePhoto();
}
}
public class NikonAdapter : ICameraAPIAdapter
{
public NikonAPI NikonAPI { get; set;}
public NikonAdapter(NikonAPI nikonAPI)
{
this.NikonAPI = nikonAPI;
}
public void Shoot()
{
this.NikonAPI.PhotoShoot();
}
}
Usage
ICameraAPIAdapter adapter = new CanonAdapter(new CanonAPI());
adapter.Shoot();
Comments
Post a Comment