ReactNote icon indicating copy to clipboard operation
ReactNote copied to clipboard

《深入设计模式》—— 适配器模式

Open BUPTlhuanyu opened this issue 3 years ago • 0 comments

在原有的代码片段中,这样使用 Target 类的:

/**
 * The Target defines the domain-specific interface used by the client code.
 */
class Target {
    public request(): string {
        return 'Target: The default target\'s behavior.';
    }
}
function clientCode(target: Target) {
    console.log(target.request());
}

同时原来的代码还存在这样的类,可能会被其他 clinet 使用,如下:

/**
 * The Adaptee contains some useful behavior, but its interface is incompatible
 * with the existing client code. The Adaptee needs some adaptation before the
 * client code can use it.
 */
class Adaptee {
    public specificRequest(): string {
        return '.eetpadA eht fo roivaheb laicepS';
    }
}
function clientCodeOther(target: Adaptee) {
    console.log(target.specificRequest());
}

现在,我的客户端代码中需要在 clientCode 中使用 Adaptee 的 specificRequest 的输出结果,那么在不修改 clientCode 的情况下,我们可以使用 适配器模式 来实现:

/**
 * The Adapter makes the Adaptee's interface compatible with the Target's
 * interface.
 */
class Adapter extends Target {
    private adaptee: Adaptee;

    constructor(adaptee: Adaptee) {
        super();
        this.adaptee = adaptee;
    }

    public request(): string {
        const result = this.adaptee.specificRequest().split('').reverse().join('');
        return `Adapter: (TRANSLATED) ${result}`;
    }
}

const adaptee = new Adaptee();
const adapter = new Adapter(adaptee);
clientCode(adapter);

BUPTlhuanyu avatar Oct 14 '21 06:10 BUPTlhuanyu