Javascript模拟实现适配器模式

模拟场景

利用适配器模式实现外籍球员通过翻译者(相当于实现语言转换的适配器) ,在接受不同训练指令(即接口调用)时,与其他球员以一致的训练指令进行训练的过程

在上述设计的场景中将球员分为三类,即前锋(Forwards)、中锋(Center)、后卫(Guards),同时每类球员的训练指令简化为:进攻(Attack)和防守(Defense)两种。此外,设定有一位外籍中锋球员,该球员通过翻译接受命令进行训练。

普通前锋、中锋、后卫类的创建

class Forwards{
    constructor(name) {
        this.name = name;
    }
    attack(){
        console.log(`前锋${this.name}进攻`);
    }
    defense(){
        console.log(`前锋${this.name}防守`);
    }
}

class Center{
    constructor(name) {
        this.name = name;
    }
    attack(){
        console.log(`中锋${this.name}进攻`);
    }
    defense(){
        console.log(`中锋${this.name}防守`);
    }
}

class Guards{
    constructor(name) {
        this.name = name;
    }
    attack(){
        console.log(`后卫${this.name}进攻`);
    }
    defense(){
        console.log(`后卫${this.name}防守`);
    }
}

特殊的外籍中锋类创建

class ForeignCenter {
    constructor(name) {
        this.name = name;
    }
    进攻(){
        console.log(`外籍中锋${this.name}进攻`);
    }
    防守(){
        console.log(`外籍中锋${this.name}防守`);
    }
}

翻译类的创建,这里由为了达成教练下达同一命令的原因,以作者目前的水平,在翻译类的翻译方法中只能根据不同的指令实例化两个对象,如读者有更好的方法,望告知。

class Translator {
    constructor(name) {
        this.name = name;
    }
    fanyi(type){
        let wjzf = new ForeignCenter(this.name);
        if(type === 'att'){
            wjzf.进攻();
        }else if(type === 'def'){
            wjzf.防守();
        }
    }
    attack(){
        this.fanyi('att');
    }
    defense(){
        this.fanyi('def');
    }
}

指令的发布

let b = new Forwards("巴蒂尔");
b.attack();

let m = new Guards("麦克格雷迪");
m.attack();

let ym = new Translator("姚明");
ym.attack();
ym.defense();

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值