<?php
declare(strict_types=1);
// php 技術羣:781742505
// 多個 Formatters 抽象出 Formatter 接口
// 多個 Services 抽象出 Service 接口
// 兩個接口之間有座橋,將兩個接口的所有實例可以任意互聯。
/**
* Interface Formatter
*/
interface Formatter
{
/**
* @param string $text
*
* @return string
*/
public function format(string $text): string;
}
/**
* Class Service
*
* @package DesignPatterns\Structural\Bridge
*/
abstract class Service
{
/**
* @var Formatter
*/
protected $implementation;
/**
* @param Formatter $printer
*/
public function __construct(Formatter $printer)
{
$this->implementation = $printer;
}
/**
* @param Formatter $printer
*/
public function setImplementation(Formatter $printer)
{
$this->implementation = $printer;
}
/**
* @return string
*/
abstract public function get(): string;
}
/**
* Class HtmlFormatter
*
* @package DesignPatterns\Structural\Bridge
*/
class HtmlFormatter implements Formatter
{
/**
* @param string $text
*
* @return string
*/
public function format(string $text): string
{
return sprintf('<p>%s</p>', $text);
}
}
/**
* Class PlainTextFormatter
*
* @package DesignPatterns\Structural\Bridge
*/
class PlainTextFormatter implements Formatter
{
/**
* @param string $text
*
* @return string
*/
public function format(string $text): string
{
return "$text";
}
}
/**
* Class PingService
*
* @package DesignPatterns\Structural\Bridge
*/
class PingService extends Service
{
/**
* @return string
*/
public function get(): string
{
return $this->implementation->format("pong");
}
}
/**
* Class HelloWorldService
*
* @package DesignPatterns\Structural\Bridge
*/
class HelloWorldService extends Service
{
/**
* @return string
*/
public function get(): string
{
return $this->implementation->format('Hello World');
}
}
echo (new HelloWorldService(new PlainTextFormatter()))->get();
echo (new HelloWorldService(new HtmlFormatter()))->get();
echo (new PingService(new PlainTextFormatter()))->get();
echo (new PingService(new HtmlFormatter()))->get();
橋模式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.