运用共享技术有效的支持大量细粒度的对象
享元,就是分享元素的意思,跟注册当时的意思差不多,注册到一个容器中,这个是保存在享元工厂中,有就返回,没有就实例化然后返回,
一般池技术就是享元模式的重要实现方式,string常量池,数据库连接池,缓冲池等,
有对象的外部状态跟内部状态,内部状态时确定这个类的,共享,不能修改,外部状态就是参数,不共享能修改,
一个类实例化之后,放在享元工厂中,通过内部状态判断,
<?php
/**
* 接口类
*/
interface Flyweight
{
public function operation($extrinsicState): void;
}
/**
* 接口实现类共享
*/
class ConcreteFlyweight implements Flyweight
{
//内部状态,共享
private $template;
function __construct($temp)
{
//实例化确定
$this->template = $temp;
}
//外部状态不共享
public function operation($extrinsicState): void
{
echo $this->template . '方棋子方位:' . $extrinsicState . PHP_EOL;
}
}
/**
* 接口实现类不共享
*/
class UnsharedConcreteFlyweight implements Flyweight
{
//内部状态,共享
private $template;
function __construct($temp)
{
//实例化确定
$this->template = $temp;
}
//外部状态不共享
public function operation($extrinsicState): void
{
echo $this->template . '方棋子方位:' . $extrinsicState . PHP_EOL;
}
}
/**
* 享元工厂
*/
class FlyweightFactory
{
private $flyweights;
public function getFlyweight($key)
{
if (!array_key_exists($key, $this->flyweights)) {
echo '创建实例:' . $key . PHP_EOL;
$this->flyweights[$key] = new ConcreteFlyweight($key);
}
echo '拿到实例:' . $key . PHP_EOL;
return $this->flyweights[$key];
}
public function count()
{
echo '实例数量:' . count($this->flyweights) . PHP_EOL;
}
}
//实例化享元工厂
$factory = new FlyweightFactory();
//获取一个实例
$flA = $factory->getFlyweight('黑');
$flA->operation('七右之十四');
$factory->count();
$flA = $factory->getFlyweight('黑');
$flA->operation('七右之六');
$factory->count();
//获取一个实例
$flA = $factory->getFlyweight('白');
$flA->operation('六右之三');
$factory->count();
$flA = $factory->getFlyweight('白');
$flA->operation('六右之六');
$factory->count();
//非共享
$Unshared = new UnsharedConcreteFlyweight('彩');
$Unshared->operation('六右之六');