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.
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].