Adapter,Pattern

Erhan 8/7/2016 0

Adapter Pattern

C#
 Most of you might have heard about Adapter Pattern. It is a pattern commonly used
in our applications but without knowing it. Adapter Pattern is one among the 23
Design Patterns. In this chapter I would like to examine this pattern using a simple
example.
Challenge
You are working on a Square class. You need to find the Area of it using Calculator
class. But the Calculator class only takes Rectangle class as input. How to solve this
scenario?
Definition
GoF Definition: "Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn't otherwise because of incompatible
interfaces."

The CalculatorAdapter performs the following functions:
. Takes the Square parameter
. Convert Square to Rectangle
. Call the original Calculator.GetArea() method
. Return the value received

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AdapterPattern
{
    public class Calculator
    {
        public int GetArea(Rectangle rectangle)
        {
            int area = rectangle.Width * rectangle.Height;

            return area;
        }
    }

    public class Rectangle
    {
        public int Width;
        public int Height;
    }

    public class Square
    {
        public int Size;
    }

    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;
        }
    }
}

************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AdapterPattern
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void CalculateButton_Click(object sender, EventArgs e)
        {
            // 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();
        }
    }
}

  
 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments