Home > Backend Development > PHP Tutorial > PHP Adapter Pattern Object Adaptation Code Analysis

PHP Adapter Pattern Object Adaptation Code Analysis

黄舟
Release: 2023-03-06 16:40:02
Original
1348 people have browsed it

PHPAdapter patternObjectAdaptation code analysis

<?php
// 适配器模式-对象适配

/**
 * 需要被适配的类
 * 需求:给 Source 新增一个新的方法但又不修改 Source 的源代码
 */
class Source
{
	public function action() {
		echo &#39;call action&#39;, &#39;<br/>&#39;;
	}
}

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 &#39;call <b>action2</b>&#39;, &#39;<br/>&#39;;
	}
}

// test code
$s = new Source();
$ad = new Adapter($s);

$ad->action();
$ad->action2();
Copy after login

The above is the detailed content of PHP Adapter Pattern Object Adaptation Code Analysis. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template