Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
BUPTlhuanyu opened this issue Oct 14, 2021 · 0 comments
Open

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

BUPTlhuanyu opened this issue Oct 14, 2021 · 0 comments

Comments

@BUPTlhuanyu
Copy link
Owner

在原有的代码片段中,这样使用 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant