Friday, April 09, 2021

Adapter design pattern c#

This example illustrates the structure of the Adapter design pattern. It focuses on answering these questions:
  • What classes does it consist of?
  • What roles do these classes play?
  • In what way the elements of the pattern are related?
We start with by createing a file called Adaptee. The Adaptee contains some useful behavior, but its interface is incompatible with the existing client code. The Adaptee needs some adaptation before the client code can use it.
class Adaptee
{
   public string GetSpecificRequest()
   {
       return "Specific request.";
   }
}
Next we create the interface ITarget The Target defines the domain-specific interface used by the client code.
public interface ITarget
{
   string GetRequest();
}
The Adapter class will br extended with the ITarget interface. The Adapter makes the Adaptee's interface compatible with the ITarget's interface.
class Adapter : ITarget
{
   private readonly Adaptee _adaptee;

   public Adapter(Adaptee adaptee)
   {
       this._adaptee = adaptee;
   }

   public string GetRequest()
   {
       return $"This is '{this._adaptee.GetSpecificRequest()}'";
   }
}
We put this all together in the Main method in the Program class file.
static void Main(string[] args)
{
   Adaptee adaptee = new Adaptee();
   ITarget target = new Adapter(adaptee);

   Console.WriteLine("Adaptee interface is incompatible with the client.");
   Console.WriteLine("But with adapter client can call it's method.");

   Console.WriteLine(target.GetRequest());
}
When we compile and run we should get:
Adaptee interface is incompatible with the client.
But with adapter client can call it's method.
This is 'Specific request.'

The Ray Code is AWESOME!!!
wikipedia

Find Ray on:

facebook
youtube
The Ray Code
Ray Andrade

The Strategy Design Pattern a Behavioral Pattern using C++

The Strategy Design Pattern is a behavioral design pattern that enables selecting an algorithm's implementation at runtime. Instead of i...