Home  >  Article  >  Backend Development  >  A simple example of interface adaptation in PHP adapter mode

A simple example of interface adaptation in PHP adapter mode

黄舟
黄舟Original
2017-03-15 09:47:271327browse

PHPAdapter patternInterfaceSimple example of adaptation

<?php
// 适配器模式-接口适配

/**
 * 问题:实现此接口的类需要实现所有的方法,但是实际使用的仅仅是其中的某一个方法而已,比较繁琐
 * 解决方法:增加一个中间类,对所有的方法空实现,然后不再直接实现接口而是继承这个中间类
 * 这就是 接口适配.
 */
interface Sourceable
{
	function action1();
	function action2();
	function action3();
}

/**
 * 中间类, 所有方法空实现
 */
abstract class AbstractAdapter implements Sourceable
{
	public function action1() { }
	public function action2() { }
	public function action3() { }
}

class Adapter extends AbstractAdapter
{
	public function action2() {
		echo &#39;call <b>action2</b>&#39;, &#39;<br/>&#39;;
	}
}

class Adapter2 extends AbstractAdapter
{
	public function action3() {
		echo &#39;call <b>action3</b>&#39;, &#39;<br/>&#39;;
	}
}

// test code
$a1 = new Adapter();
$a1->action2();

$a2 = new Adapter2();
$a2->action3();

The above is the detailed content of A simple example of interface adaptation in PHP adapter mode. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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