<?php
// 适配器模式-对象适配
/**
* 需要被适配的类
* 需求:给 Source 新增一个新的方法但又不修改 Source 的源代码
*/
class Source
{
public function action() {
echo 'call action', '<br/>';
}
}
interface Targetable
{
/**
* Source 类中同名的方法,
* 适配器中不需要使用的方法可以不在此接口中定义
*/
function action();
/**
* 需要给 Source 类新增的方法
*/
function action2();
}
/**
* 适配器类
* 相对于 类适配 更加灵活
*/
class Adapter implements Targetable
{
/**
* 不是继承 Source 类, 而是持有 Source 类的实例
*/
private $sou = null;
public function construct(Source $s) {
$this->sou = $s;
}
public function action() {
$this->sou->action();
}
public function action2() {
echo 'call <b>action2</b>', '<br/>';
}
}
// test code
$s = new Source();
$ad = new Adapter($s);
$ad->action();
$ad->action2();以上就是PHP适配器模式之对象适配代码分析的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号