目的
為了節約記憶體的使用,享元模式會盡量使類似的物件共享記憶體,在大量類似物件被使用的情況中這是十分必要的,常用做法是在外部資料結構中保存類似物件的狀態,并在需要時將他們傳遞給享元物件,
UML 圖

★官方PHP高級學習交流社群「點擊」管理整理了一些資料,BAT等一線大廠進階知識體系備好(相關學習資料以及筆面試題)以及不限于:分布式架構、高可擴展、高性能、高并發、服務器性能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell腳本、Docker、微服務、Nginx等多個知識點高級進階干貨
代碼
- FlyweightInterface.php
<?php
namespace DesignPatterns\Structural\Flyweight;
/**
* 創建享元介面 FlyweightInterface ,
*/
interface FlyweightInterface
{
/**
* 創建傳遞函式,
* 回傳字串格式資料,
*/
public function render(string $extrinsicState): string;
}
- CharacterFlyweight.php
<?php
namespace DesignPatterns\Structural\Flyweight;
/**
* 假如可以的話,實作享元介面并增加記憶體存盤內部狀態,
* 具體的享元實體被工廠類的方法共享,
*/
class CharacterFlyweight implements FlyweightInterface
{
/**
* 任何具體的享元物件存盤的狀態必須獨立于其運行環境,
* 享元物件呈現的特點,往往就是對應的編碼的特點,
*
* @var string
*/
private $name;
/**
* 輸入一個字串物件 $name,
*/
public function __construct(string $name)
{
$this->name = $name;
}
/**
* 實作 FlyweightInterface 中的傳遞方法 render() ,
*/
public function render(string $font): string
{
// 享元物件需要客戶端提供環境依賴資訊來自我定制,
// 外在狀態經常包含享元物件呈現的特點,例如字符,
return sprintf('Character %s with font %s', $this->name, $font);
}
}
- FlyweightFactory.php
<?php
namespace DesignPatterns\Structural\Flyweight;
/**
* 工廠類會管理分享享元類,客戶端不應該直接將他們實體化,
* 但可以讓工廠類負責回傳現有的物件或創建新的物件,
*/
class FlyweightFactory implements \Countable
{
/**
* @var CharacterFlyweight[]
* 定義享元特征陣列,
* 用于存盤不同的享元特征,
*/
private $pool = [];
/**
* 輸入字串格式資料 $name,
* 回傳 CharacterFlyweight 物件,
*/
public function get(string $name): CharacterFlyweight
{
if (!isset($this->pool[$name])) {
$this->pool[$name] = new CharacterFlyweight($name);
}
return $this->pool[$name];
}
/**
* 回傳享元特征個數,
*/
public function count(): int
{
return count($this->pool);
}
}
測驗
- Tests/FlyweightTest.php
<?php
namespace DesignPatterns\Structural\Flyweight\Tests;
use DesignPatterns\Structural\Flyweight\FlyweightFactory;
use PHPUnit\Framework\TestCase;
/**
* 創建自動化測驗單元 FlyweightTest ,
*/
class FlyweightTest extends TestCase
{
private $characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
private $fonts = ['Arial', 'Times New Roman', 'Verdana', 'Helvetica'];
public function testFlyweight()
{
$factory = new FlyweightFactory();
foreach ($this->characters as $char) {
foreach ($this->fonts as $font) {
$flyweight = $factory->get($char);
$rendered = $flyweight->render($font);
$this->assertEquals(sprintf('Character %s with font %s', $char, $font), $rendered);
}
}
// 享元模式會保證實體被分享,
// 相比擁有成百上千的私有物件,
// 必須要有一個實體代表所有被重復使用來顯示不同單詞的字符,
$this->assertCount(count($this->characters), $factory);
}
}
PHP 互聯網架構師成長之路*「設計模式」終極指南
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)
面試10家公司,識訓9個offer,2020年PHP 面試問題
★如果喜歡我的文章,想與更多資深開發者一起交流學習的話,獲取更多大廠面試相關技術咨詢和指導,歡迎加入我們的群啊,暗號:phpzh(君羊號碼856460874),
2020年最新PHP進階教程,全系列!

內容不錯的話希望大家支持鼓勵下點個贊/喜歡,歡迎一起來交流;另外如果有什么問題 建議 想看的內容可以在評論提出
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/60939.html
標籤:PHP
