Guide to Using Adapter Pattern with C#
Guide to Using Adapter Pattern with C#
Design patterns in software development have a significant impact on code reusability, maintainability, and extensibility. The Adapter Pattern is one of these design patterns and serves to connect two incompatible interfaces. In this article, you will learn how to use the Adapter Pattern in C#.
What is the Adapter Pattern?
The Adapter Pattern is used when the interface of an object is converted to another interface that is expected, resolving incompatibilities between two objects. This pattern allows existing classes to be used without modification. For instance, when a new component is added to a system, there may be a need to use an adapter to make it compatible with the old components.
Example Scenario
Let's assume we are developing an application to manage a swimming pool. In our application, we have classes that represent two different types of swimmers: LocalSwimmer and ForeignSwimmer. While local swimmers work directly compatible with the system, foreign swimmers might require an adapter. This is exactly where the Adapter Pattern comes into play.
Implementation of Adapter Pattern with C#
Now, let's implement the adapter pattern in C#. First, we will define our swimmer interface:
public interface IYuzucu
{
void Yuz();
}
Then, let's define the local swimmer class:
public class YerliYuzucu : IYuzucu
{
public void Yuz()
{
Console.WriteLine("The local swimmer is swimming.");
}
}
The foreign swimmer needs to be made compatible with an adapter:
public class YabancıYuzucu
{
public void Swim()
{
Console.WriteLine("The foreign swimmer is swimming.");
}
}
Finally, let's define the adapter class that will make the foreign swimmer compatible:
public class YabancıYuzucuAdapter : IYuzucu
{
private YabancıYuzucu _yabancıYuzucu;
public YabancıYuzucuAdapter(YabancıYuzucu yabancıYuzucu)
{
_yabancıYuzucu = yabancıYuzucu;
}
public void Yuz()
{
_yabancıYuzucu.Swim();
}
}
Now let’s test a swimmer using this structure:
public class Program
{
public static void Main(string[] args)
{
IYuzucu yerliYuzucu = new YerliYuzucu();
yerliYuzucu.Yuz(); // The local swimmer is swimming.
YabancıYuzucu yabancıYuzucu = new YabancıYuzucu();
IYuzucu adapter = new YabancıYuzucuAdapter(yabancıYuzucu);
adapter.Yuz(); // The foreign swimmer is swimming.
}
}
Conclusion
The Adapter Pattern is a powerful pattern that enables objects to be made compatible. With this pattern, you can make your code more modular and add new features without changing your existing classes. Implementing this pattern in a robust language like C# makes your software development process modern and efficient.

Yorum Gönder