C# Corner

The Adapter Pattern in the .NET Framework

The Adapter Pattern allows incompatible interfaces to communicate. Learn how it works by building an application that calculates prime numbers.

The Adapter Pattern is a common software design pattern that allows you to adapt one interface into another interface that the client expects. The Adapter Pattern is particularly useful for allowing two incompatible interfaces to communicate via the adapter.

The adapter pattern has three main components: the target class, the adapter class and the adaptee interface. The adaptee is an existing interface that gets adapted by the adapter to the target class. An adapter class is also commonly referred to as a wrapper class for the adaptee class.

Let's look at a complete example of the adapter pattern. Say that you have an existing legacy adaptee interface called PrimeSolver. PrimeSolver allows you to find the nearest prime number to a given number via a method called CalculatePrime. It has a new target interface, PrimeDirective, with a method named FindNearestPrime that replaces CalculatePrime.

You'd like to use the old legacy code but keep the new interface. To tackle this problem, you can create an adapter class that wraps the legacy interface and exposes the new interface to the client. The client gets the benefit of the new interface, and doesn't need to worry about the old legacy system behind the scenes.

To get started, create a new C# Console App and add the IPrimeSolver adaptee interface, which contains a single method named CalculatePrime:

namespace VSMAdapterPatternDemo
{
    public interface IPrimeSolver
    {
        int CalculatePrime(int number);
    }
}

Next add the IPrimeDirective target interface with its FIndNearestPrime method:

namespace VSMAdapterPatternDemo
{
    public interface IPrimeDirective
    {
        int FindNearestPrime(int number);
    }
}

Then add the IPrimeDirectiveAdapter interface that provides a contract for adapting to the IPrimeDirective interface:

namespace VSMAdapterPatternDemo
{
    public interface IPrimeDirectiveAdapter
    {
        int FindNearestPrime(int number);
    }
}

Now, it's time to employ the PrimeSolver class. The PrimeSolver class implements the old legacy IPrimeSolver interface. It contains a single method, CalculatePrime, that finds the nearest prime number to the given number, as seen in Listing 1. The algorithm for finding prime numbers is available at CodeProject.

Listing 1: PrimeSolver.cs

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

namespace VSMAdapterPatternDemo
{
    public class PrimeSolver : IPrimeSolver
    {
        public int CalculatePrime(int number)
        {
            var primes = Primes(number);
            return primes.Max();
        }

        // Code from http://www.codeproject.com/Tips/257269/Find-Prime-Numbers-in-Csharp-Quickly?msg=4199032#xx4199032xx.
        private IEnumerable<int> Primes(int bound)
        {
            if (bound < 2) yield break;
            //The first prime number is 2
            yield return 2;

            //Create a sieve of 'half size' starting at 3
            BitArray notPrime = new BitArray((bound - 1) >> 1);
            int limit = ((int)(Math.Sqrt(bound)) - 1) >> 1;
            for (int i = 0; i < limit; i++)
            {
                if (notPrime[i]) continue;
                //The first number not crossed out is prime
                int prime = 2 * i + 3;
                yield return prime;
                //cross out all multiples of this prime, starting at the prime squared
                for (int j = (prime * prime - 2) >> 1; j < notPrime.Count; j += prime)
                {
                    notPrime[j] = true;
                }
            }
            //The remaining numbers not crossed out are also prime
            for (int i = limit; i < notPrime.Count; i++)
            {
                if (!notPrime[i]) yield return 2 * i + 3;
            }
        }
    }
}

Next, implement the PrimeSolverToPrimeDirectiveAdapter class that adapts the old IPrimeSolver interface into the new IPrimeDirective interface. The adapter class instantiates an instance of the PrimeSolver class and calls its CalculatePrime method for the FindNearestPrime IPrimeDirectiveAdapter wrapper method:

namespace VSMAdapterPatternDemo
{
    public class PrimeSolverToPrimeDirectiveAdapter : IPrimeDirectiveAdapter, IPrimeDirective
    {
        private readonly PrimeSolver _primeSolver;

        public PrimeSolverToPrimeDirectiveAdapter()
        {
            _primeSolver = new PrimeSolver();
        }

        public int FindNearestPrime(int number)
        {
            return _primeSolver.CalculatePrime(number);
        }
    }
}

The last step is to test out the PrimeSolverToPrimeDirectiveAdapter in the Program class. First, create a new adapter class:

var primeDirective = new PrimeSolverToPrimeDirectiveAdapter();
Then get a number from the user, calculate the result and display it:

int num;
 Console.WriteLine("Enter a number to find its nearest prime:");
 int.TryParse(Console.ReadLine(), out num);
 int result = primeDirective.FindNearestPrime(num);
 Console.WriteLine("The nearest prime to {0} is {1}.", num, result);

Here's the completed Program class implementation.

using System;

namespace VSMAdapterPatternDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var primeDirective = new PrimeSolverToPrimeDirectiveAdapter();
            int num;
            Console.WriteLine("Enter a number to find its nearest prime:");
            int.TryParse(Console.ReadLine(), out num);
            int result = primeDirective.FindNearestPrime(num);
            Console.WriteLine("The nearest prime to {0} is {1}.", num, result);
            Console.ReadLine();
        }
    }
}

You should now be able to run the finished program, enter a number and find its nearest prime, as seen in Figure 1.

[Click on image for larger view.] Figure 1. The completed application.

As you can see, the Adapter Pattern is a very useful design pattern to know. Its primary use is to translate one interface into a new compatible interface for the client application. The pattern is also great for wrapping hard-to-test code to increase your code coverage.

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube