javascript 适配器结构设计模式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 适配器结构设计模式相关的知识,希望对你有一定的参考价值。

## Real world example
Consider that you have some pictures in your memory card and you need to transfer them to your computer. In order to transfer them you need some kind of adapter that is compatible with your computer ports so that you can attach memory card to your computer. In this case card reader is an adapter. Another example would be the famous power adapter a three legged plug can't be connected to a two pronged outlet, it needs to use a power adapter that makes it compatible with the two pronged outlet. Yet another example would be a translator translating words spoken by one person to another

## In plain words
Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.

## Wikipedia says
In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.
/*
Lion interface :

roar()
*/

class AfricanLion  {
    roar() {}
}

class AsianLion  {
    roar() {}
}

class Hunter {
    hunt(lion) {
        // ... some code before
        lion.roar()
        //... some code after
    }
}


// This needs to be added to the game
class WildDog {
    bark() {
    }
}

// Adapter around wild dog to make it compatible with our game
class WildDogAdapter {

    constructor(dog) {
        this.dog = dog;
    }
    
    roar() {
        this.dog.bark();
    }
}


// IMPLEMENTATION
wildDog = new WildDog()
wildDogAdapter = new WildDogAdapter(wildDog)

hunter = new Hunter()
hunter.hunt(wildDogAdapter)

以上是关于javascript 适配器结构设计模式的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript设计模式——适配器模式

javascript设计模式——适配器模式

JavaScript设计模式 Item9 --适配器模式Adapter

JavaScript设计模式与开发实践 适配器模式

深入理解JavaScript系列(39):设计模式之适配器模式

从ES6重新认识JavaScript设计模式: 适配器模式