问题:已经存在一个类,但是已经不满足现有需求,源代码不方便随意更改
解决方法:
适配器创建与一个现有的对象兼容的接口
//目标 class Target { public function request() { return "Target: The default target's behavior."; } } //需要被适配的类Adaptee class Adaptee { public function specificRequest() { return ".eetpadA eht fo roivaheb laicepS"; } } //适配器Adapter class Adapter extends Target { private $adaptee; //依赖注入的方式调用Adaptee,也可以在类用extends和implements实现2继承,但是implements为继承接口的 public function __construct(Adaptee $adaptee) { $this->adaptee = $adaptee; } public function request() { return "Adapter: (TRANSLATED) " . strrev($this->adaptee->specificRequest()); } } //客户端调用接口 function clientCode(Target $target) { echo $target->request(); } echo "Client: I can work just fine with the Target objects:<br/>"; $target = new Target(); clientCode($target); echo "<br/>"; $adaptee = new Adaptee(); echo "Client: The Adaptee class has a weird interface. See, I don't understand it:<br/>"; echo "Adaptee: " . $adaptee->specificRequest(); echo "<br/>"; echo "Client: But I can work with it via the Adapter:<br/>"; $adapter = new Adapter($adaptee); clientCode($adapter);执行结果:
Client: I can work just fine with the Target objects: Target: The default target's behavior. Client: The Adaptee class has a weird interface. See, I don't understand it: Adaptee: .eetpadA eht fo roivaheb laicepS Client: But I can work with it via the Adapter: Adapter: (TRANSLATED) Special behavior of the Adaptee.参考:https://refactoringguru.cn/design-patterns/adapter/php/example
https://www.jianshu.com/p/d06f9c35636d