
上两节我们介绍了创建型设计模式中的五种。今天我们继续学习结构型设计模型,它们分别是:
- 适配器
- 桥接
- 组合
- 装饰
- 门面
- 享元
- 代理
适配器
当对象的属性或方法需要从一个转换到另一个时,使用适配器设计模式。当具有不匹配接口的组件必须相互协作时,该模式非常有用。适配器模式也称为包装器模式。
让我们通过我们的玩具工厂来理解这一点:
- 玩具厂有一个运输部门。
- 我们正计划从旧的运输部门迁移到新的运输部门。
- 但是,对于当前库存,我们需要保持旧的运输方式不变。
// old interface
function Shipping() {
this.request = function (zipStart, zipEnd, weight) {
// ...
return "$49.75";
}
}
// new interface
function AdvancedShipping() {
this.login = function (credentials) { /* ... */ };
this.setStart = function (start) { /* ... */ };
this.setDestination = function (destination) { /* ... */ };
this.calculate = function (weight) { return "$39.50"; };
}
// adapter interface
function ShippingAdapter(credentials) {
var shipping = new AdvancedShipping();
shipping.login(credentials);
return {
request: function (zipStart, zipEnd, weight) {
shipping.setStart(zipStart);
shipping.setDestination(zipEnd);
return shipping.calculate(weight);
}
};
}
function run() {
var shipping = new Shipping();
var credentials = { token: "StarWars-001" };
var adapter = new ShippingAdapter(credentials);
// original shipping object and interface
var cost = shipping.request("78701", "10010", "2 lbs");
console.log("Old cost: " + cost);
// new shipping object with adapted interface
cost = adapter.request("78701", "10010", "2 lbs");
console.log("New cost: " + cost);
}
总结:
适配器模式将接口不兼容的组件改造成兼容的接口。适配器对象和原始接口对于外部API来说是一致的,在这个例子中其实就是request方法。