js设计模式之Structural Patterns------Adapter(1)

本文探讨了在面对复杂接口时使用适配器模式来简化其应用的方法。通过一个具体的例子——将复杂的Ship接口转换为更简洁的SimpleShip接口,展示了如何通过创建适配器类来实现这一目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述
The interface of the implementation does not look the way we would like it to for use
in our code. Normally the solution to this is to simply refactor the implementation
so it looks the way we would like it to. However, there are a number of possible
reasons that cannot be done. Perhaps the implementation exists inside third party
code to which we have no access. It is also possible that the implementation is used
elsewhere in the application where the interface is exactly as we would like it to be.

The adapter class is a thin piece of code that implements the required interface. It
typically wraps a private copy of the implementation class and proxy calls through
to it. The adapter pattern is frequently used to change the abstraction level of the
code.

If we look at the interface for a Ship in Westeros, it looks intimidating:

interface Ship{
   SetRudderAngleTo(angle: number);
   SetSailConfiguration(configuration: SailConfiguration);
   SetSailAngle(sailId: number, sailAngle: number);
   GetCurrentBearing(): number;
   GetCurrentSpeedEstimate(): number;
   ShiftCrewWeightTo(weightToShift: number, locationId: number);
}

I would really like a much simpler interface that abstracts away all the fiddly little details. Ideally something like the following:

interface SimpleShip{
    TurnLeft();
    TurnRight();
    GoForward();
}
let ShipAdapter = (function () {
    function ShipAdapter() {
        this._ship = new Ship();
    }
    ShipAdapter.prototype.TurnLeft = function () {
        this._ship.SetRuddlerAngleTo(-30);
        this._ship.setSailAngle(3,12);
    };
    ShipAdapter.prototype.TurnRight = function () {
        this._ship.SetRuddlerAngleTo(30);
        this._ship.setSailAngle(5, -9);
    };
    ShipAdapter.prototype.GoForward = function () {

    };
    return ShipAdapter;
})();

var ship = new ShipAdapter();
ship.GoForward();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值