php 实现设计模式之 享元模式
<?php class Book{ public $title; public $author; public function __construct($title,$author){ $this->author = $author; $this->title = $title; } public function getTitle(){ return $this->title; } public function getAuthor(){ return $this->author; } } class BookFactory{ public $books; public function add($book){ $this->books[] = $book; } public function getBook($title){ if(empty($this->books[$title])){//建立title和book的对应关系。 $this->books[$title] = new Book($title, '李白'); } return $this->books[$title]; } } class BookShelf{ public $shelf; public function add($book){ $this->shelf[] = $book; } public function show(){ foreach ($this->shelf as $value){ echo '作者 :'.$value->getAuthor().' 标题:'.$value->getTitle(); echo "<br/>"; } } } class Client{ public static function main(){ $obj = new BookFactory(); $shelf = new BookShelf(); $book_1 = $obj->getBook('静夜思'); $book_2 = $obj->getBook('望天门山'); $book_3 = $obj->getBook('望庐山瀑布'); $book_4 = $obj->getBook('静夜思');//book4 服用的book1. if($book_1 === $book_4){ echo 'book1 is as the same as book4'; } $shelf->add($book_1); $shelf->add($book_2); $shelf->add($book_3); $shelf->show(); } } Client::main(); ?>
UML类图如下:
补充一个实例:
<?php //一个产品有ISBN号和名字 class Product{ public $ISBN; public $name; } //享元类,提取出共性,同一个ISBN号对应的名字不会变,把这本书名字提取出来,放入享元对象,这样享元对象就存储了内蕴状态,外蕴状态是ISBN号码 class Book{ public $name; public function __construct($name){ $this->name = $name; } public function show(){ echo $this->name; } } //享元对象生产工厂,传入外蕴对象,返回对应的享元对象。 class BookFactory{ public $books = array(); public function getBook($ISBN,$name){//维护一个对象池 if(!isset($this->books[$ISBN])){ $this->books[$ISBN] = new Book($name); } return $this->books[$ISBN]; } } $obj = new BookFactory(); $book = $obj->getBook('1111','PHP高级程序设计'); $book2 = $obj->getBook('1111',''); $book2->show(); ?>