PHP設計模式之-----適配器模式

<?php
//適配器要完成的功能很明確,引用現有接口的方法實現新的接口的方法。
//你的接口不改的話,我就利用現有接口和你對接一下吧。
//“開-閉”原則,一個軟件實體應當對擴展開放,對修改關閉
//http://www.cnblogs.com/DeanChopper/p/4770572.html

/**
 * Class Toy
 *
 * @describe 原有的接口
 *
 * @author   nick
 *
 */
abstract class Toy
{
	public abstract function openMonth();

	public abstract function closeMonth();
}

class Dog extends Toy
{

	public function openMonth()
	{
		echo '狗張嘴';
	}

	public function closeMonth()
	{
		echo '狗閉嘴';
	}
}

class Cat extends Toy
{

	public function openMonth()
	{
		echo '貓張嘴';
	}

	public function closeMonth()
	{
		echo '貓閉嘴';
	}
}

// 目標公司 紅棗公司
interface RedTarget
{
	public function doMonthOpen();

	public function doMonthClose();
}

// 目標公司 綠棗公司
interface GreenTarget
{
	public function operateMouth( $type = 0 );
}

// 紅棗公司適配器
class ReaAdapter implements RedTarget
{
	private $adaptee;
	// 只是接受 Toy 的子類
	public function __construct( Toy $adaptee )
	{
		$this->adaptee = $adaptee;
	}

	public function doMonthOpen()
	{
		$this->adaptee->openMonth();
	}

	public function doMonthClose()
	{
		$this->adaptee->closeMonth();
	}
}

// 綠棗公司適配器
class GreenAdapter implements GreenTarget
{
	private $adaptee;

	public function __construct(Toy $adaptee) {
		$this->adaptee=$adaptee;
	}

	public function operateMouth( $type = 0 )
	{
		if($type){
			$this->adaptee->openMonth();
		}else{
			$this->adaptee->closeMonth();
		}
	}
}

class testDriver
{
	public function run(){
		// 實例化一個玩具
		$adaptee_dog = new Dog();
		// 紅棗公司適配器
		echo '紅棗公司適配器';
		$adapter_red  = new ReaAdapter($adaptee_dog);
		$adapter_red->doMonthOpen();
		$adapter_red->doMonthClose();
		// 綠棗公司適配器
		$adaptee_green = new GreenAdapter($adaptee_dog);
		$adaptee_green->operateMouth(1);
		$adaptee_green->operateMouth(0);
	}
}
$test = new testDriver();
$test->run();








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章