细粒的有效地这个模式有效地使用共享来支持大量的细粒度对象
Client(客户端)
This class (a) maintains a reference to a flyweight, and (b) computes or stores the extrinsic([ek'strinsik] 外在地) state of flyweight(s).
(这类(a)维护一个轻量级选手的引用,和(b)计算或存储轻量级选手的外在的状态。)
UnsharedConcreteFlyweight(不共享具体享元)
Not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing; it doesn't enforce it.
(并不是所有的轻量级选手子类需要共享。Flyweight接口允许共享;它不强制它。)
ConcreteFlyweight(具体享元)
This class implements the Flyweight interface and adds storage(存储) for intrinsic(固有的) state, if any.
(这个类实现了轻量级选手接口,并为固有的状态添加存储,如果有。)
Flyweight(享元)
This class declares an interface through which flyweights can receive and act on extrinsic state.
(这类声明一个接口,能通过flyweights在外部状态接收并行动。)
FlyweightFactory(享元工厂)
This class (a) creates and manages flyweight objects, and (b) ensures that flyweights are shared properly(适当地).
(这类(a)创建和管理flyweight对象,和(b)适当地确保flyweight 是共享的。)
<?php
$flyweightFactory = new FlyweightFactory();
$flyweights = $flyweightFactory->getFlyweights('artist1');
class ConcreteFlyweight implements Flyweight
{
private $_name;
public function __construct($name) {
echo "construct " . $name . "";
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
}
interface Flyweight
{
public function getName();
}
class FlyweightFactory
{
private $_flyweights = array();
public function getFlyweights($name) {
if (isset($this->_flyweights[$name])) {
return $this->_flyweights[$name];
} else {
$concreteFlyweight = new ConcreteFlyweight($name);
$this->_flyweights[$name] = $concreteFlyweight;
return $concreteFlyweight;
}
}
}
评论