简介:这是php设计模式 FlyWeight (享元模式)的详细页面,介绍了和php,有关的知识、技巧、经验,和一些php源码等。
class='pingjiaF' frameborder='0' src='http://biancheng.dnbcw.info/pingjia.php?id=339152' scrolling='no'>1 <?php
2 /**
3 * 享元模式
4 *
5 * 运用享元技术有效的支持大量细粒度的对象
6 */
7 class CD
8 {
9 private $_title = null;
10 private $_artist = null;
11
12 public function setTitle($title)
13 {
14 $this->_title = $title;
15 }
16
17 public function getTitle()
18 {
19 return $this->_title;
20 }
21
22 public function setArtist($artist)
23 {
24 $this->_artist = $artist;
25 }
26
27 public function getArtist($artist)
28 {
29 return $this->_artist;
30 }
31 }
32
33 class Artist
34 {
35 private $_name;
36
37 public function __construct($name)
38 {
39 echo "construct ".$name."<br/>";
40 $this->_name = $name;
41 }
42
43 public function getName()
44 {
45 return $this->_name;
46 }
47 }
48
49 class ArtistFactory
50 {
51 private $_artists = array();
52
53 public function getArtist($name)
54 {
55 if(isset($this->_artists[$name]))
56 {
57 return $this->_artists[$name];
58 } else {
59 $objArtist = new Artist($name);
60 $this->_artists[$name] = $objArtist;
61 return $objArtist;
62 }
63 }
64 }
65
66 $objArtistFactory = new ArtistFactory();
67
68 $objCD1 = new CD();
69 $objCD1->setTitle("title1");
70 $objCD1->setArtist($objArtistFactory->getArtist('artist1'));
71
72 $objCD2 = new CD();
73 $objCD2->setTitle("title2");
74 $objCD2->setArtist($objArtistFactory->getArtist('artist2'));
75
76 $objCD3 = new CD();
77 $objCD3->setTitle("title3");
78 $objCD3->setArtist($objArtistFactory->getArtist('artist1'));