为了节约内存的使用,享元模式会尽可能使相似的对象共享内存。在大量相似对象被使用的状况中这是十分必要的。经常使用作法是在外部数据结构中保存相似对象的状态,并在须要时将他们传递给享元对象。php
<?php namespace DesignPatterns\Structural\Flyweight; /** * 建立享元接口 FlyweightInterface 。 */ interface FlyweightInterface { /** * 建立传递函数。 * 返回字符串格式数据。 */ public function render(string $extrinsicState): string; }
<?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); } }
<?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); } }
<?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 互联网架构师 50K 成长指南+行业问题解决总纲(持续更新)sql
面试10家公司,收获9个offer,2020年PHP 面试问题shell
★若是喜欢个人文章,想与更多资深开发者一块儿交流学习的话,获取更多大厂面试相关技术咨询和指导,欢迎加入咱们的群啊,暗号:phpzh(君羊号码856460874)。设计模式
内容不错的话但愿你们支持鼓励下点个赞/喜欢,欢迎一块儿来交流;另外若是有什么问题 建议 想看的内容能够在评论提出服务器