享元模式
享元模式(Flyweight Pattern):運用共享技術有效地支援大量細粒度對象的複用。系統隻使用少量的對象,而這些對象都很相似,狀态變化很小,可以實作對象的多次複用。由于享元模式要求能夠共享的對象必須是細粒度對象,是以它又稱為輕量級模式,它是一種對象結構型模式。
模式結構
享元模式包含如下角色:
- Flyweight: 抽象享元類
- ConcreteFlyweight: 具體享元類
- UnsharedConcreteFlyweight: 非共享具體享元類
- FlyweightFactory: 享元工廠類
結構圖
PHP代碼實作
<?php
/**
* 享元模式
*/
abstract class Flyweight {
abstract public function operation($state);
}
//具體享元角色
class ConcreteFlyweight extends Flyweight {
private $state = null;
public function __construct($state) {
$this->state = $state;
}
public function operation($state) {
var_dump('具體Flyweight:'.$state);
}
}
//不共享的具體享元,用戶端直接調用
class UnsharedConcreteFlyweight extends Flyweight {
private $state = null;
public function __construct($state) {
$this->state = $state;
}
public function operation($state) {
var_dump('不共享的具體Flyweight:'.$state);
}
}
//享元工廠角色
class FlyweightFactory {
private $flyweights;
public function __construct() {
$this->flyweights = array();
}
public function getFlyweigth($state) {
if (isset($this->flyweights[$state])) {
return $this->flyweights[$state];
} else {
return $this->flyweights[$state] = new ConcreteFlyweight($state);
}
}
}
$f = new FlyweightFactory();
$a = $f->getFlyweigth('state A');
$a->operation("other state A");
$b = $f->getFlyweigth('state B');
$b->operation('other state B');
/* 不共享的對象,單獨調用 */
$u = new UnsharedConcreteFlyweight('state A');
$u->operation('other state A');
運作結果
string '具體Flyweight:other state A' (length=)
string '具體Flyweight:other state B' (length=)
string '不共享的具體Flyweight:other state A' (length=)