PHP设计模式-适配器模式

2021/11/17 11:10:44

本文主要是介绍PHP设计模式-适配器模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、概述

将一个类的接口转换成兼容接口,使原本由于接口不兼容不能一起工作的类可以一起工作,通俗的讲:将已经存在的的类创建一个“中间类”,用户直接调用该中间类

二、核心

  1. 属于结构型设计模式
  2. 将不同规格的设备通过统一规格的适配器对接到你的系统中
  3. 常用于和第三方库结合使用,因为第三方库的代码不允许修改

三、结构图

在这里插入图片描述
四、代码示例

<?php
/*
 * 适配器模式
 */


/*
 * 类Cat和Dog已经存在,我们需要设计适配器类继承主类,对外开放统一调用
 */
class Cat
{
    public function eatfish()
    {
        return "Cat eat fish!";
    }
}

class Dog
{
    public function eatBone()
    {
        return "Dog eat Bone!";
    }
}

/*
 * 设计适配器类
 */
interface Adapter
{
    public function Eat();
}

class CatAdapter extends Cat implements Adapter
{
    public function Eat()
    {
        return $this->eatfish();
    }
}

class DogAdapter extends Dog implements Adapter
{
    public function Eat()
    {
        return $this->eatBone();
    }
}

/*
 * 主业务
 */

class Animal
{
    private $adapter;

    public function __construct($obj)
    {
        $this->adapter = $obj;
    }

    public function Eat()
    {
        return $this->adapter->Eat();
    }

}

//小猫吃东西
$catObj = new CatAdapter();
$animal = new Animal($catObj);
$animal->Eat();

//小狗吃东西
$dogObj = new DogAdapter();
$animal = new Animal($dogObj);
$animal->Eat();

五、总结

  1. 其中CatClass和DogClass为原始类,在不修改的情况下,用户想要灵活调用类中的eatfish(eatBone)方法,可以为该类加上适配器
    CatAdpterClass和DogAdpterClass


这篇关于PHP设计模式-适配器模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程