Convert the interface of a class into another interface that the clients expects(Adapter Pattern)

Adapter Pattern

Adapter pattern:

    class Program
    {
        static IExpectedInterface dependency = new Adapter(new TargetClass());
        static void Main(string[] args)
        {
            dependency.MethodA();
        }
    }
    public interface IExpectedInterface
    {
        void MethodA();
    }
    public class Adapter : IExpectedInterface
    {
        public Adapter(TargetClass target)
        {
            this.target = target;
        }
        public void MethodA()
        {
            target.MethodB();
        }
        private TargetClass target;
    }
    public class TargetClass
    {
        public void MethodB()
        {
        }
    }

Advantages of using a Adaptor pattern:

  • Adapter pattern lets classes work together that couldn’t otherwise because of incompatible interfaces.
  • The code is more maintainable.
  • most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.