Home » Design Pattern » Adapter

Adapter

作者:

分類:

Adapter

Adapter Concept

The Adapter pattern (a.k.a Wrapper, similar to the Decorator pattern) is a structural design pattern commonly used to wrap a pre-existing class. It allows a class to work with others without altering the core, by encapsulating it with an additional layer.

In practical software development, situations often arise where there is a need to integrate external libraries (DLL). The challenge is to incorporate additional functionality without affecting the core.

Consider a scenario where an existing system already has functionality for controlling a light source with methods for turning it On/Off.

Now, the goal is to integrate a new controller into the system. The new controller also has methods for turning on & off, but even if the method has same names, they cannot be directly used due to the absence of a shared interface.

Adapter Example

//*************
//* author: cian
//* 20231017
//**************

/* Adapter Interface */
interface ILightControl
{
    void Open();
    void Close();
}

class SomeLightControllerAdapter : ILightControl
{
    private SomeLightController adaptee = new SomeLightController();

    public void Open()
    {
        adaptee.LightOpen(); //method wrapped.
    }

    public void Close()
    {
        adaptee.LightClose(); //method wrapped.
    }
}

class MainApp
{
    static void Main(string[] args)
    {
        var lightList = new List<ILightControl>();
        lightList.add(new OriginLightController());
        lightList.add(new SomeLightControllerAdapter());
        
        foreach (var item in lightList)
        {
            item.Open();
        }
    }
}

Personally, I think Adapter pattern is a common application of interfaces, especially for those who have experience working with external APIs. It’s easy to grasp the concept if you’ve experienced in system integration.

References

cian Avatar

留言

Leave a Reply

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