学习php设计模式 php实现享元模式(flyweight)(2)

八、复合享元模式
复合享元模式对象是由一些单纯享元使用合成模式加以复合而成
复合享元角色所代表的对象是不可以共享的,但是一个复合享元对象可以分解成为多个本身是单纯享元对象的组合。
九、复合享元模式PHP示例

<?php /** * 抽象享元角色 */ abstract class Flyweight { /** * 示意性方法 * @param string $state 外部状态 */ abstract public function operation($state); } /** * 具体享元角色 */ class ConcreteFlyweight extends Flyweight { private $_intrinsicState = null; /** * 构造方法 * @param string $state 内部状态 */ public function __construct($state) { $this->_intrinsicState = $state; } public function operation($state) { echo 'ConcreteFlyweight operation, Intrinsic State = ' . $this->_intrinsicState . ' Extrinsic State = ' . $state . '<br />'; } } /** * 不共享的具体享元,客户端直接调用 */ class UnsharedConcreteFlyweight extends Flyweight { private $_flyweights; /** * 构造方法 * @param string $state 内部状态 */ public function __construct() { $this->_flyweights = array(); } public function operation($state) { foreach ($this->_flyweights as $flyweight) { $flyweight->operation($state); } } public function add($state, Flyweight $flyweight) { $this->_flyweights[$state] = $flyweight; } } /** * 享元工厂角色 */ class FlyweightFactory { private $_flyweights; public function __construct() { $this->_flyweights = array(); } public function getFlyweigth($state) { if (is_array($state)) { // 复合模式 $uFlyweight = new UnsharedConcreteFlyweight(); foreach ($state as $row) { $uFlyweight->add($row, $this->getFlyweigth($row)); } return $uFlyweight; } else if (is_string($state)) { if (isset($this->_flyweights[$state])) { return $this->_flyweights[$state]; } else { return $this->_flyweights[$state] = new ConcreteFlyweight($state); } } else { return null; } } } /** * 客户端 */ class Client { /** * Main program. */ public static function main() { $flyweightFactory = new FlyweightFactory(); $flyweight = $flyweightFactory->getFlyweigth('state A'); $flyweight->operation('other state A'); $flyweight = $flyweightFactory->getFlyweigth('state B'); $flyweight->operation('other state B'); /* 复合对象*/ $uflyweight = $flyweightFactory->getFlyweigth(array('state A', 'state B')); $uflyweight->operation('other state A'); } } Client::main(); ?>

十、PHP中享元模式的地位
相对于其它模式,Flyweight模式在PHP的现有版本中没有太大的意义,因为PHP的生命周期是页面级的,即从一个PHP文件执行开始会载入所需的资源,当执行完毕后,这些所有的资源会被全部释放,而一般来说我们也不会让一个页面执行太长时间。

以上就是使用php实现享元模式的代码,还有一些关于享元模式的概念区分,希望对大家的学习有所帮助。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/8b95e4d45bb3fec9ad7e8139f6a184ba.html