What is Adapter pattern?
The adapter pattern is adapting between classes and objects.Explanation
Like any adapter in the real world it is used to be an interface, a bridge between two objects.In real world we have adapters for power supplies, adapters for camera memory cards, and so on. Probably everyone have seen some adapters for memory cards. If you can not plug in the camera memory in your laptop you can use and adapter.You plug the camera memory in the adapter and the adapter in to laptop slot.
public class Rectangle
{
public int Width;
public int Height;
}
public class Calculator
{
public int GetArea(Rectangle rectangle)
{
int area = rectangle.Width * rectangle.Height;
return area;
}
}
As we cn see from the above example an instance of Rectangle is needed to calculate the area. If we have a square class of definition below, the calculation cannot be done.
public class Square
{
public int Size;
}
Here we have to create a new CalculatorAdapter to get the work done.
public class CalculatorAdapter
{
public int GetArea(Square square)
{
Calculator calculator = new Calculator();
Rectangle rectangle = new Rectangle();
rectangle.Width = rectangle.Height = square.Size;
int area = calculator.GetArea(rectangle);
return area;
}
}
The CalculatorAdapter performs the following functions:
· Takes the Square parameter
· Convert Square to Rectangle
· Call the original Calculator.GetArea() method
· Return the value received
The invoking code is shown below:
// Create Square class and assign Size from UI
Square square = new Square();
square.Size = SquarePanel.Width;
// Use Adapter to calculate the area
CalculatorAdapter adapter = new CalculatorAdapter();
int area = adapter.GetArea(square);
// Display the result back to UI
ResultLabel.Text = “Area: ” + area.ToString();
No comments:
Post a Comment