享元模式(Flyweight Pattern)

百度词条的解释

http://baike.baidu.com/view/6143765.htm

<?php
//享元模式
//抽象享元角色(Flyweight)
abstract class Character {

	private $symbol;
	private $width;
	private $height;
	private $ascent;
	private $descent;
	private $pointSize;

	public abstract function display($pointSize);
}

//具体享元(ConcreteFlyweight)角色
class CharacterA extends Character {

	public function __construct() {
		$this->symbol = 'A';
		$this->height = 100;
		$this->width = 120;
		$this->ascent = 70;
		$this->descent = 0;
	}

	public function display($pointSize) {
		//不可享元的成员
		$this->pointSize = $pointSize;
		echo $this->symbol.'(pointSize'.$this->pointSize.')<br/>';
	}

}

//具体享元(ConcreteFlyweight)角色
class CharacterB extends Character {

	public function __construct() {
		$this->symbol = 'B';
		$this->height = 100;
		$this->width = 140;
		$this->ascent = 72;
		$this->descent = 0;
	}

	public function display($pointSize) {
		//不可享元的成员
		$this->pointSize = $pointSize;
		echo $this->symbol.'(pointSize'.$this->pointSize.')<br/>';
	}

}

//享元工厂(FlyweightFactoiy)角色
class CharacterFactory {

	private $characters = array();

	public function __set($key, $value) {
		$this->$key = $value;
	}

	public function __get($key) {
		if(isset($this->$key)) {
			return $this->$key;
		} else {
			return NULL;
		}
	}

	public function getCharacter($key) {
		$character = @$this->characters[$key];
		if(empty($character)) {
			$className = 'Character'.$key;
			echo '实例化了一次'.$className.'<br/>';
			$character = new $className();
			$this->characters[$key] = $character;
		}
		return $character;
	}
}

$document = 'AABBA';
$chars = str_split($document);
$characterFactory = new CharacterFactory();

$pointSize = 10;

foreach($chars as $k => $v) {
	$pointSize++;
	$character = $characterFactory->getCharacter($v);
	$character->display($pointSize);
}
?>


你可能感兴趣的:(享元模式(Flyweight Pattern))