@Chiang
2020-01-03T10:42:08.000000Z
字数 2144
阅读 518
设计模式
- 享元抽象类
- 共享的具体享元类
- 不共享的具体享元类
- 享元工厂
<?php
/**
* Flyweight.php
*
* @author Luffy <lufei@swoole.com>
* @date 2019/12/9
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Flyweight;
abstract class Flyweight
{
/**
* @var
*/
protected $name;
/**
* Flyweight constructor.
* @param $name
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* @param $content
*/
abstract public function get($content);
}
<?php
/**
* ConcreteFlyweight.php
*
* @author Luffy <lufei@swoole.com>
* @date 2019/12/9
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Flyweight;
class ConcreteFlyweight extends Flyweight
{
/**
* @param $content
*/
public function get($content)
{
echo "共享的:{$content} {$this->name}\n";
}
}
<?php
/**
* UnsharedConcreteFlyweight.php
*
* @author Luffy <lufei@swoole.com>
* @date 2019/12/9
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Flyweight;
class UnsharedConcreteFlyweight extends Flyweight
{
/**
* @param $content
*/
public function get($content)
{
echo "不共享的:{$content} {$this->name}\n";
}
public function del()
{
$this->name = '';
}
}
<?php
/**
* FlyweightFactory.php
*
* @author Luffy <lufei@swoole.com>
* @date 2019/12/9
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Flyweight;
class FlyweightFactory
{
/**
* @var array
*/
private $flyweights = [];
/**
* @param $name
* @return mixed
*/
public function getFlyweight($name)
{
if (!isset($this->flyweights[$name])) {
$this->flyweights[$name] = new ConcreteFlyweight($name);
}
return $this->flyweights[$name];
}
}
<?php
/**
* Client.php
*
* @author Luffy <lufei@swoole.com>
* @date 2019/12/9
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Flyweight;
include __DIR__ . '/../vendor/autoload.php';
class Client
{
public static function run()
{
$flyweight = new FlyweightFactory();
$obj1 = $flyweight->getFlyweight("⭐️");
$obj1->get('第1个');
$obj2 = $flyweight->getFlyweight("⭐️");
$obj2->get('第50个');
var_dump($obj1 === $obj2);
$obj3 = $flyweight->getFlyweight("🍎");
$obj3->get('第1个');
// 不共享的
$obj4 = new UnsharedConcreteFlyweight("🍍");
$obj4->get("一");
$obj4->del();
$obj4->get("一");
}
}
Client::run();