适配器设计模式的解释


Adapter design pattern explained

以下是我对适配器设计模式的理解

你有一个遗留的支付系统:

class LegacyPaymentSystem {
    public function pay($amount) {
    }
    public function refund() {
    }
}

你实现了一个新的支付系统:

class PaymentSystem {
   public function __construct() { 
   }
   public function payAmount($amount, $currency) {
   }
   public function refund($payment_id) {
   }
}

您使用适配器来桥接两者。有时你想使用旧的支付系统。

 class PaymentSystemAdapter extends PaymentSystem {
    public function __construct($legacyPaymentSystem) {
       $this->legacyPaymentSystem = $legacyPaymentSystem;
    }
    public function payAmount($amount, $currency) {
         $this->legacyPaymentSystem->pay($amount);
    }   
}

现在客户端可以做:

class Client { 
    public function process($amount, $currency) {
        $legacyPaymentSystem  = new LegacyPaymentSystem();
        $adapter = new PaymentSystemAdapter($legacyPaymentSystem);
        $this->pay($adapter, $amount, $currency);
    }
    public function pay(PaymentSystem $paymentSystem, $amount, $currency) {
        $payementSystem->payAmount($amount, $currency);
    }
}

我的问题是为什么?为什么我们不能直接调用遗留支付系统呢?

通常,Client应该只访问PaymentSystem,并且应该不知道它正在使用的实现。

class Client { 
    public function process($amount, $currency) {
        $paymentSystem  = lookupPaymentSystem();
        $payementSystem->payAmount($amount, $currency);
    }
}

适配器模式允许通过向客户端公开统一的接口来隐藏各种实现的本质,即使底层实现具有不同的接口。

它允许你坚持一个叫做的设计原则,程序到接口,而不是实现