码迷,mamicode.com
首页 > Web开发 > 详细

php模式设计

时间:2015-08-07 00:13:23      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

1,策略模式

2,个体模式

3,工厂模式

4,观察者模式

技术分享
 1 <?php
 2 class ExchangeRate
 3 {
 4     static private $instance = NULL;
 5     private $observers = array();
 6     private $exchange_rate;
 7 
 8     static function getInstance()
 9     {
10         if (self::$instance == NULL)
11             self::$instance = new ExchangeRate();
12         return self::$instance;
13     }
14     public function registerObserver($obj)
15     {
16         $this->observers[] = $obj;
17     }
18     public function getExchangeRate()
19     {
20         return $this->exchange_rate;
21     }
22     public function setExchangeRate($new_rate)
23     {
24         $this->exchange_rate = $new_rate;
25         $this->notifyObservers();
26 
27     }
28     function notifyObservers()
29     {
30         foreach ($this->observers as $obj) {
31             # code...
32             $obj->notify($this);
33         }
34     }
35 
36 
37 }
38 
39 class ProductItem
40 {
41     public function __construct()
42     {
43         ExchangeRate::getInstance()->registerObserver($this);
44 
45     }
46     public function notify($obj)
47     {
48         if($obj instanceof ExchangeRate) print "Received update!\n";
49     }
50 }
51 
52 
53 
54 $a = new ProductItem();
55 $b = new ProductItem();
56 ExchangeRate::getInstance()->setExchangeRate(4.5);
57 
58 
59 
60 ?>
View Code

 

php模式设计

标签:

原文地址:http://www.cnblogs.com/liunnis/p/4709437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!