PHP设计模式-适配器模式

本文介绍了PHP设计模式中的适配器模式,旨在解决接口不兼容问题,允许不同规格的设备通过适配器接入同一系统。适配器模式属于结构型模式,常见于与第三方库的整合。文中通过代码示例展示了如何为原始类CatClass和DogClass创建适配器类,以实现用户灵活调用eatfish或eatBone方法。
摘要由CSDN通过智能技术生成

一、概述

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

二、核心

  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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瞎玩儿~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值