适配器模式(Adapter Pattern)
|
1 2 3 |
定义:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。 目的:主要解决在软件系统中,常常要将一些"现存的对象"放到新的环境中,而新环境要求的接口是现对象不能满足的。 场景:系统需要使用现有的类,而此类的接口不符合系统的需要。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
class Target { constructor() { if (new.target === Target) { throw new Error('Target 是抽象类,不能直接实例化') } } small() { throw new Error('子类必须实现 small() 方法') } } class Adaptee { big() { console.log('执行新的接口') return '执行成功' } } class Adapter extends Target { constructor(adaptee) { super() if (typeof adaptee?.big !== 'function') { throw new TypeError('被适配对象必须提供 big() 方法') } this.adaptee = adaptee } small() { return this.adaptee.big() } } const adaptee = new Adaptee() const target = new Adapter(adaptee) const result = target.small() console.log(result) // 执行成功 |

