zoukankan      html  css  js  c++  java
  • php设计模式-适配器模式

    适配器模式其实也是一种为了解耦的设计模式,为了让客户端的调用变得更简单统一,将源接口转换为目标接口的过程封装到特定的过程中,这个过程就叫适配。

    逻辑图如下:

    将特定的需要适配的类作为装饰器的一个成员变量进行注入,然后再暴露同一个调用接口。

    具体代码如下:

    <?php
    /**
     * Created by PhpStorm.
     * User: tonny
     * Date: 2019/7/15
     * Time: 20:44
     */
    
    interface Target
    {
        public function charge();
    }
    
    class Adapter implements Target
    {
        protected $adaptee = null;
        public function __construct($adaptee)
        {
            $this->adaptee = $adaptee;
    
        }
    
        public function charge()
        {
            $className = get_class($this->adaptee);
            if ($className == 'StreetEl') {
                $this->adaptee->shareCharge();
            } else if ($className == 'Battery') {
                $this->adaptee->selfCharge();
            }
        }
    }
    
    class StreetEl
    {
        public function shareCharge()
        {
            echo "share way to charge it!
    ";
        }
    }
    
    class Battery
    {
        public function selfCharge()
        {
            echo "self charging by battrey!
    ";
        }
    }
    
    $streeEl = new StreetEl();
    $battery = new Battery();
    $adapter = new Adapter($streeEl);
    $adapter->charge();

    这样代码的可扩展性和复用性能够很大的提高,也符合“开闭原则”。当然它也有坏处,可能会造成调用复杂,比如调用的是A,实际是调用的C

    当然还有更符合php特色的写法,将需要适配的类的初始化也放到Adapter的构造函数里面,利用字符串变量来动态new对象。在这里只为了阐述通用型的适配器模式,就不展开说了。

  • 相关阅读:
    linux下光标定位和清屏函数
    使用NHibernate的时候出现“指定的转换无效”的错误
    UI 界面:技术决定一切
    BeamTarget红外线的末尾
    Chicken的代码解剖:6 PlayerController
    kismet模块创建
    Projectile重构
    关卡设计师优化关卡
    一些主类的继承关系
    EA iOS平台《质量效应》《死亡空间》的界面
  • 原文地址:https://www.cnblogs.com/freephp/p/11191572.html
Copyright © 2011-2022 走看看