HooneyLog

Adapter Pattern

프로필 이미지

Seunghoon Shin

2022년 7월 31일 02:10

What is Adapter Pattern?

this pattern allow you to make different classes with different interfaces to work together without changing your source code. you can see this in your real life like Android phone and IPhone.

Let’s make a code example about that situation how you can implement at typescript.

Example

interface IIPhone {
    useLigthening:()=>void;
}

interface IAndroid {
    useMicroPin:()=>void;
}

class IPhone implements IIPhone {
    useLigthening() {
        console.log("being charged by lightening")
    }
}

class Galaxy implements IAndroid{
    useMicroPin() {
        console.log("being charged by micro pin");
    }
}

class LighteningToMicropinAdapter implements IAndroid{
    iphone:IPhone;

    constructor(iphone:IPhone) {
        this.iphone = iphone
    }

    useMicroPin() {
        console.log("using micro pin, which is converting to lightening");
        this.iphone.useLigthening();
    }
}

Conclusion

This is good to use an existing class, but its interface does not match for a thing you need.

you can extend your code without any changes of the class and can make your classes to work together and be compatible, which is about “The Open-Closed Principle”, one of SOLID principle.