js設計模式之Structural Patterns------Adapter(1)

這裏寫圖片描述
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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章