[php]php设计模式 FlyWeight (享元模式)

1 <?php
2 /**
3 * 享元模式
4 *
5 * 运用享元技术有效的支持大量细粒度的对象
6 */
7 class CD
8 {
9 private$_title=null;
10 private$_artist=null;
11
12 publicfunction setTitle($title)
13 {
14 $this->_title =$title;
15 }
16
17 publicfunction getTitle()
18 {
19 return$this->_title;
20 }
21
22 publicfunction setArtist($artist)
23 {
24 $this->_artist =$artist;
25 }
26
27 publicfunction getArtist($artist)
28 {
29 return$this->_artist;
30 }
31 }
32
33 class Artist
34 {
35 private$_name;
36
37 publicfunction __construct($name)
38 {
39 echo"construct ".$name."<br/>";
40 $this->_name =$name;
41 }
42
43 publicfunction getName()
44 {
45 return$this->_name;
46 }
47 }
48
49 class ArtistFactory
50 {
51 private$_artists=array();
52
53 publicfunction 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'));

posted on 2011-06-23 22:26  bluefrog  阅读(1152)  评论(0编辑  收藏  举报