设计模式学习系列——适配器模式

适配器模式

  适配器模式(Adapter Pattern),是将一种接口改造成另外一种接口的一个包装类。

  适用场景:系统需要使用现有的类,但是此类的接口不符合系统的需要。

  优点: 1.提高了类的复用;2.增加了类的透明度;3灵活性好。

  缺点:使用太多,会显得系统凌乱,增加系统的复杂度。适配器不会在系统设计的时候添加,一般只是用在对现有系统进行改进的时候使用。

  角色:

  1)目标接口

  2)适配器类

  3)适配者类

  4)使用者

考虑以下场景,笔记本是5V电源(假设是5V),需要连一个220v的电源,这个时候需要个适配器。参考以下代码:

  1 <?php
  2 /*
  3  * 适配器方法模式示例
  4  */
  5 error_reporting(E_ALL);
  6 ini_set('display_errors','on');
  7 
  8 
  9 /*
 10  * 角色:目标接口
 11  * 接口类——电源
 12  */
 13 interface Source{
 14     public function output($EAVoltage);
 15 }
 16 /*
 17  * 角色;适配者类
 18  * 实现类——220V电源
 19  */
 20 class Source220V implements Source{
 21     const VOLTAGE = "220V";
 22     public function output($EAVoltage){
 23         if($EAVoltage == self::VOLTAGE){
 24             return self::VOLTAGE;
 25         }else{
 26             return "";
 27         }
 28     }
 29     public function getVoltage(){
 30         return self::VOLTAGE;
 31     }
 32 }
 33 
 34 /*
 35  * 角色;适配者类
 36  * 实现类——5V电源
 37  */
 38 class Source5V implements Source{
 39     const VOLTAGE = "5V";
 40     public function output($EAVoltage){
 41         if($EAVoltage == self::VOLTAGE){
 42            return self::VOLTAGE;
 43         }else{
 44             return false;
 45         }
 46     }
 47     public function getVoltage(){
 48         return self::VOLTAGE;
 49     }
 50 }
 51 
 52 /*
 53  * 接口类——适配器
 54  */
 55 interface Adapter  {
 56     public function input(Source $source);
 57     public function output($EAVoltage);
 58 }
 59 
 60 /*
 61  * 角色;适配器(组合方式)
 62  * 实现类——220V转5V
 63  * 实现了适配器
 64  */
 65 class Adapter220V implements Source{
 66     private $source;
 67     
 68     public function output($EAVoltage){
 69         if($EAVoltage == "220V"){
 70             $this->source = new Source220V();
 71             return $this->source->output("220V");
 72         }
 73         if($EAVoltage == "5V"){
 74             $this->source = new Source5V();
 75             return $this->source->output("5V");
 76         }
 77         return false;
 78     }
 79 }
 80 
 81 /*
 82  * 角色;使用类
 83  * 笔记本 
 84  */
 85 class NoteBook {
 86     const VOLTAGE = "5V";
 87     /*
 88      * 开机
 89      */
 90     public function powerOn(){
 91         $source = new Adapter220V();
 92         if($source->output(self::VOLTAGE) == self::VOLTAGE){//采用output方法无需关注实现细节
 93             return true;
 94         }else{
 95             return false;
 96         } 
 97     }
 98 }
 99 
100 $noteBook = new NoteBook;
101 var_dump($noteBook->powerOn());//bool(true)
View Code

  

猜你喜欢

转载自www.cnblogs.com/Andres/p/8962332.html