類圖
插座轉換
德標接口
interface DBSocketInterface
{
public function powerWithTwoRound();
}
實現德標的德國插座
class DBSocket implement DBSocketInterface
{
public function powerWithTwoRound()
{
echo "使用兩項圓頭的插孔供電";
}
}
德國酒店
class Hotel
{
private $dbSocket;
public function setSocket(DBSocketInterface $dbSocket)
{
$this->dbSocket = $dbSocket;
}
public function charge()
{
$this->dbSocket->powerWithTwoRound();
}
}
國標接口
interface GBSocketInterface
{
public function powerWithThreeFlat();
}
實現國標的中國插座
class GBSocket
{
public function powerWithThreeFlat()
{
echo "使用三項扁頭的插孔供電";
}
}
適配器(插頭轉換 接口轉換)
class SocketAdatper implements DBSocketInterface
{
private $gbSocket;
public function __construct(GBSocketInterface $gbSocket)
{
$this->gbSocket = $gbSocket;
}
public function powerWithTwoRound()
{
$this->gbSocket->powerWithThreeRound;
}
}
測試
$gbSocket = new GBSocket();
$hotel = new Hotel();
$socketAdapter = new SocketApapter($gbSocket);
$hotel->setSocket($socketApapter);
$hotel->charge();